Sending network Requests

  • Install axio
npm install axios -D
Copy the code
  • Request writing location (send request after component has rendered JSX syntax)
class App extends Component {
  constructor () {
    super(a)this.state = {
      // Store the requested data
      msg: ' '
    }
  }
  render () {
    return (
      <div>
        {this.state.msg}
      </div>)}// Network requests must be made in
  async componentDidMount () {
    const text = await axios.get('http://localhost:3005/api/welcome')
    // Store the requested and received data in the state and display it on the interface
    this.setState({
      msg: text.data.msg
    })
  }
}
Copy the code

Forward requests

What is request forwarding

PS :(not finished)

When is request forwarding used

PS: In general, during the development process, we run a port used by the project, but our data comes from other servers, which will lead to cross-domain requests, so that the data cannot be normally requested back and displayed on the interface

The process of requesting a forward

PS: The client application sends a request to the same-origin server. The server forwards the request to the API server. The API server processes the data and then returns it to the client for use

Note: There is no cross-domain problem on the server side

React How to forward requests

  • In the package configuration
"proxy": "Address you want to forward to (http://localhost:3005)"
Copy the code

PS: After the configuration, it is necessary to find the location of the request, delete the previous address and retain the later one, so that the current running port will be automatically splices during the runtime, the project needs to be re-run, and the cache needs to be cleared

async componentDidMount () {
    							// Automatically join the current project running port
    const text = await axios.get('/api/welcome')
    // Store the requested and received data in the state and display it on the interface
    this.setState({
      msg: text.data.msg
    })
}
Copy the code

PS: Disadvantages: Only one address can be configured, and different addresses store different data during development. Therefore, this method is not recommended


  • Using third-party plug-ins
npm i http-proxy-middleware
Copy the code
  • Forward using the methods provided
const { createProxyMiddleware } = require('http-proxy-middleware')

module.exports = app= > {
  app.use('/api',createProxyMiddleware({
    target: 'http://localhost:3005'.changeOrigin:true}}))Copy the code

PS: Use multiple uses for multiple requests

The mock data

In the development process, front-end and back-end development in parallel, front-end development process, request a certain interface, need data, this is the back-end interface can not be used normally, want to show the data, you need to simulate the data