Create a stage

Create a ProxyAgent folder

React scaffolding creation

  1. inProxyAgentRun in the folder pathnpx create-react-app proxy-agent-appGenerate a React scaffold.
  2. Modify thepublicUnder folderindex.htmlFile, deletesrcFolder under all files, newly createdindex.jsandApp.jsxFile.
  3. React Scaffolding pathnpm i axiosThe installationaxios
  4. To run the scaffold, open oneterminal, command line inputcd proxy-agent-appEnter the current scaffold pathnpm startRun scaffolding.
  5. Scaffolding runs onhttp://localhost:3000/, that is,Port 3000.

Express Server Creation

  1. ProxyAgentCreate a server folder in the folder path, run in the folder pathnpm i expressInstall the Express framework.
  2. Internal createserver1.jsserver2.js
  3. If you want to run this server, start another oneterminal, command line inputcd serverTo the server folder path, enternode server1.jsCommand to runserver1The server
  4. server1Running on thehttp://localhost:8000/, that is,Port 8000.

Cross-domain problem phase occurs

When the scaffolding requests data in port 8000 from port 3000, cross-domain will occur, and the browser will report an error:

Server1 received a request from ternimal on the react side. Server1 received a request from ternimal on the react side. “, indicating that the request has been successfully received by port 8000.

When the 3000 client sends a request to the 8000 server, it goes through the Ajax engine, sends it successfully, but when the data in response comes back, it goes through the Ajax engine, and at this point it’s intercepted by the Ajax engine, because it’s across domains.

Proxy Proxy refers to the role of a middleman, which is opened on port 3000. Port 3000 is not only running the React scaffolding, but also running a Proxy server. When the React client sends a request, the 3000 client sends the request to the agent, which then sends the request to the 8000 server. The 8000 server returns the corresponding data to the proxy server, which then sends the data back to the React client.

In this case, the 8000 server can return data to the proxy server on port 3000 because the cross-domain response is essentially intercepted by the AJAX engine in the React client. However, since the proxy server does not have an AJAX engine, there is no cross-domain problem. The same-origin policy does not limit the proxy, and the proxy is only responsible for forwarding.

Specific code

// The contents of server1.js file in the server folder

// 1. Introduce express
const express = require("express");

// 2. Create application objects
const app = express();

// If someone requests server1, the internal words are printed
app.use((request, response, next) = > {
    console.log("Someone has requested server 1...")
    next()
})

// 3. Create a route rule GET request
// Request encapsulates request packets
// Response encapsulates the response message
app.get("/students".(request, response) = > {
    const students = [
        {id:"001".name:"Zhang".age:10},
        {id:"002".name:"Bill".age:20},
        {id:"003".name:"Fifty".age:30}]// Set the response
    response.send(students);
})

// 4. Listen to the port to start the service

app.listen(8000.(error) = > {
    if(! error) {console.log("Service has been launched, request the server address is: http://localhost:8000/students");}
})
Copy the code

// react the contents of the index.js file in the scaffolding

import React, { Component } from 'react'
import ReactDOM from "react-dom"
import App from "./App.jsx"

export default class Index extends Component {
    render() {
        return (
            <div>
                <App></App>
            </div>
        )
    }
}
ReactDOM.render(<Index />.document.getElementById("root"))
Copy the code
// React the contents of the index.js file in the scaffolding

import React, { Component } from 'react'
import axios from "axios"
import "./App.css"

export default class App extends Component {
    // When the button button is clicked, a GET request is sent to server1 on port 8000 for students data
    getStudentData = () = > {
        axios.get("http://localhost:8000/students").then(
            response= > {console.log("It worked!, response.data); },error= > {console.log("Failed!, error); })}render() {
        return (
            <div>
                <button className="button" onClick={this.getStudentData}>Click to get student data on port 5000 server</button>
            </div>)}}Copy the code

Single server agent configuration phase

  1. Open the React scaffolding folderpackage.jsonFile, add one at the end"proxy": "http://localhost:8000". After that, all requests sent to 3000 will be sent to 8000.
  2. Open react scaffoldingApp.jsxThe file,axios.get("http://localhost:8000/students")toaxios.get("http://localhost:3000/students")
  3. Re-run the React scaffolding and find that data is available

Note:

Don’t write “proxy”: “Http://localhost:8000/students”, because if port 8000 return if there are students not only information, also head of the information and other information, write/students here only to find the information in the/students.

If the App. JSX document axios. Get (” http://localhost:3000/students “) to axios. Get (” http://localhost:3000/index.html “), and found that the server did not receive the request, The React scaffolding file contains all the code inside the **index. HTML file in the public folder.

This indicates that “http://localhost:3000/” is the root path of the public folder. The input after 3000/ will check whether the corresponding file exists in the public folder first. Only when no corresponding content is found in the Public folder, the server of port 8000 will be searched.

Concrete code implementation

// Package. json file with correct modifications (... Denotes internal ellipsis)

{
    "name": "proxy-agent-app"."version": "0.1.0 from"."private": true."dependencies": {... },"scripts": {... },"eslintConfig": {... },"browserslist": {... },"proxy": "http://localhost:8000"
}
Copy the code
// App.jsx file with correct modifications

import React, { Component } from 'react'
import axios from "axios"
import "./App.css"

export default class App extends Component {
    getStudentData = () = > {
        axios.get("http://localhost:3000/students").then(
            response= > {console.log("It worked!, response.data); },error= > {console.log("Failed!, error); })}render() {
        return (
            <div>
                <button className="button" onClick={this.getStudentData}>Click to get student data on port 5000 server</button>
            </div>)}}Copy the code

Multiple server agent configuration phase

Because adding a “proxy” at the end of the package.json file: “http://localhost:8000” can only add one server, it needs to change when a second server is added. So you need to find other ways to implement it:

  1. serversCreate another one in the folderserver2.jsThe content is similar toserver1.js, but the port number is changed8001.
  2. App.jsxAdd a new filebuttonUsed to getteachersThe information of
  3. Put in the configuration of a single serverpackage.jsonThe value ** added to the fileproxyDelete, undopackage.jsonFile.
  4. React scaffoldingsrcAdd a new file to the foldersetupProxy.js. This file cannot be written using ES6 syntaxCJS (CommonJS)Because this file is not for the front-end to execute, the React scaffold will find the file and add it toWebpackIn the configuration ofWebpackIt’s all used insideNodeThe syntax of, i.eCJSSyntax. Configure the file.
  5. Modify theApp.jsxThe two requests in the file areaxios.get("http://localhost:3000/api1/students")andaxios.get("http://localhost:3000/api2/teachers")
  6. Open threeterminal, run separatelyserver1.jsserver2.jsAnd React scaffolding,3000Port’s browser will display the following results.

Concrete code implementation

// App.jsx file with correct modifications

import React, { Component } from 'react'
import axios from "axios"
import "./App.css"

export default class App extends Component {
    getStudentData = () = > {
        axios.get("http://localhost:3000/api1/students").then(
            response= > {console.log("It worked!, response.data); },error= > {console.log("Failed!, error); } ) } getTeacherData =() = > {
        axios.get("http://localhost:3000/api2/teachers").then(
            response= > {console.log("It worked!, response.data); },error= > {console.log("Failed!, error); })}render() {
        return (
            <div>
                <button className="button" onClick={this.getStudentData}>Click to get student data on port 8000 server</button>
                <button className="button" onClick={this.getTeacherData}>Click to get the teacher data on port 8001 server</button>
            </div>)}}Copy the code
// The contents of server1.js file in the server folder

// 1. Introduce express
const express = require("express");

// 2. Create application objects
const app = express();

// If someone requests server1, the internal words are printed
app.use((request, response, next) = > {
    console.log("Someone has requested server 1...")
    next()
})

// 3. Create a route rule GET request
// Request encapsulates request packets
// Response encapsulates the response message
app.get("/students".(request, response) = > {
    const students = [
        {id:"001".name:"Zhang".age:10},
        {id:"002".name:"Bill".age:20},
        {id:"003".name:"Fifty".age:30}]// Set the response
    response.send(students);
})

// 4. Listen to the port to start the service
app.listen(8000.(error) = > {
    if(! error) {console.log("Service 1 has been launched, request the server address is: http://localhost:8000/students"); }})Copy the code
// The server2.js file contents in the server folder

// 1. Introduce express
const express = require("express");

// 2. Create application objects
const app = express();

Server2 will output internal words whenever someone requests it
app.use((request, response, next) = > {
    console.log("Someone has requested server 2...")
    next()
})

// 3. Create a route rule GET request
// Request encapsulates request packets
// Response encapsulates the response message
app.get("/teachers".(request, response) = > {
    const students = [
        {id:"001".name:"A".age:10},
        {id:"002".name:"Small b".age:20},
        {id:"003".name:"Little c".age:30}]// Set the response
    response.send(students);
})

// 4. Listen to the port to start the service
app.listen(8001.(error) = > {
    if(! error) {console.log("Service 2 has been launched, request the server address is: http://localhost:8001/teachers"); }})Copy the code