“This is the sixth day of my participation in the First Challenge 2022. For details: First Challenge 2022”
instructions
Front that
React itself focuses only on the interface and does not contain requests to send Ajax.
The front-end application requires Ajax requests to interact with the back-end (JSON data).
React needs to integrate third-party Ajax libraries or encapsulate them yourself.
Common ajax libraries
1. JQuery is heavy and can be referenced if necessary, but it is not recommended. Because the idea of jquery is to manipulate the DOM, React tries not to manipulate the DOM. 2. Axios is lightweight and advocates the use of 1) AXIos is an Ajax wrapper around an Xml Request object 2) uses promises and returns promise objects 3) runs on both the browser and Node server side.Copy the code
axios
Our startup port is 8000 on the back end and 3000 on the front end
The installation
npm install axios
You can see that Axios is already in the dependency
App. Use js axios
- Import axios: import axios from ‘axios’;
- Declare state, which has a variable data in it
- ComponentDidMount Life Cycle (mounted)
- Axios. get, get request mode, parameter is the URL broken after the request. Axios is a Promise object, and then is the request succeeds. We haven’t written the server-side code yet, which is the back-end excuse, so we’ll use ❓ instead
- Request success, setState to modify the value
import React from 'react' ;
import './App.css' ;
import axios from 'axios' ;
class App extends React . Component {
state = {
data : ' '
}
componentDidMount() {
axios.get('? ')
.then( res= > {
this.setState({
data : res.data.data
}, () = > console .log( this.state.data))
})
.catch( err= > console .log( "Couldn't fetch data. Error: " + err))
}
render() {
return (
<div className = 'ArticleContainer'>
{this.state.data}
</div>)}}export default App;
Copy the code
The backend interface
We request the back-end address in axios.get.
I use Django on the back end
The gitee address is gitee.com/yangyiming1…
def my_view(request) :
print("Requested.")
return JsonResponse({"data":"yes"})
Copy the code
The route to axios.get can now be filled with http://localhost:8000/my_view/
We will find cross-domain problems before there is no proxy
Thinking 🤔
Is Ajax unable to send a request because of cross-domain problems, or is there no data after the request?
We print it on the back end, and you can see it’s printed.
The agent
Same-origin address access/cross-domain
Cross-domain problems occur. Our front-end (client) port is 3000, and our back-end (server) port is 8000. An Ajax request sent from the client to the server 8000. The request is allowed by Ajax, but the server’s response is rejected when it returns to the client.
The agent is a middleman, and it’s also on port 3000, where the scaffolding is running and a tiny server is running. The request sent by 3000 to 3000 is allowed, and the middleman on port 3000 sends the request to port 8000. So why can this middleman send a request to port 8000? There is no Ajax engine on it.
erDiagram proxy-3000 ||--o{ client-3000 : ask proxy-3000 }|.. |{ server-8000 : ask
How do you configure the proxy?
Methods a
Add a proxy to package.json. This proxy address is written only to the port number, without the need for a specific route
Package. json has been modified, which will take effect only when the service is stopped and restarted.
⚠️ we still have port 8000 in the request address in axios.get(), we need to change it to 3000. That’s what we said above.
Let’s try it again. The axios. Get the request address instead of http://localhost:3000/index.html can find it request is successful. Instead of requesting the server, it requests the index.html in the scaffolding, in the public folder of port 3000. If port 3000 can be found, port 8000 will be requested. 404 is returned when there are neither.
Method 2
Our approach above only works for projects that correspond to one backend, not when we need to request multiple backends (multiple ports) at the same time.
First, remove the proxy from package.json
Create setupproxy.js in the SRC folder (name cannot be changed, the file will be found automatically). This syntax cannot use Es6, but requires common JS syntax.
// CJS requires require, cannot use import
Http-proxy-middleware is downloaded when scaffolding is initialized
const proxy = require('http-proxy-middleware')
// Expose an object
module.exports = function(app){
// Call app's use method
app.use(
proxy('/api1', {The proxy configuration is triggered when a request with the/API1 prefix is encountered
// Forward to whom
target:'http://localhost:8000'.// Let the server know from where the value of the Host field in the request header is received by the control server
changeOrigin:true.// Replace api1 with a space. Remove the request prefix to ensure that the backend server is given a normal request address
pathRewrite: {'^/api1':' '}}),// Add multiple
proxy('/api2', {target:'http://localhost:8001'.changeOrigin:true.pathRewrite: {'^/api2':' '}}}))Copy the code
The interface we requested also needs to add API1
componentDidMount() {
axios.get('http://localhost:3000/api1/my_view/')
.then( res= > {
})
.catch( err= > console .log( "Couldn't fetch data. Error: " + err))
}
Copy the code