Create a stage
Create a ProxyAgent folder
React scaffolding creation
- in
ProxyAgent
Run in the folder pathnpx create-react-app proxy-agent-app
Generate a React scaffold. - Modify the
public
Under folderindex.html
File, deletesrc
Folder under all files, newly createdindex.js
andApp.jsx
File. - React Scaffolding path
npm i axios
The installationaxios
- To run the scaffold, open one
terminal
, command line inputcd proxy-agent-app
Enter the current scaffold pathnpm start
Run scaffolding. - Scaffolding runs on
http://localhost:3000/
, that is,Port 3000.
Express Server Creation
ProxyAgent
Create a server folder in the folder path, run in the folder pathnpm i express
Install the Express framework.- Internal create
server1.js
和server2.js
- If you want to run this server, start another one
terminal
, command line inputcd server
To the server folder path, enternode server1.js
Command to runserver1
The server server1
Running 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
- Open the React scaffolding folder
package.json
File, add one at the end"proxy": "http://localhost:8000"
. After that, all requests sent to 3000 will be sent to 8000. - Open react scaffolding
App.jsx
The file,axios.get("http://localhost:8000/students")
toaxios.get("http://localhost:3000/students")
- 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:
servers
Create another one in the folderserver2.js
The content is similar toserver1.js
, but the port number is changed8001.App.jsx
Add a new filebutton
Used to getteachersThe information of- Put in the configuration of a single server
package.json
The value ** added to the fileproxy
Delete, undopackage.json
File. - React scaffolding
src
Add 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 toWebpack
In the configuration ofWebpack
It’s all used insideNode
The syntax of, i.eCJS
Syntax. Configure the file. - Modify the
App.jsx
The two requests in the file areaxios.get("http://localhost:3000/api1/students")
andaxios.get("http://localhost:3000/api2/teachers")
- Open three
terminal
, run separatelyserver1.js
,server2.js
And 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