Handling cross-domain issues in React

created at 11-12-2021 views: 13

1. Cross-domain

The cross-domain problem is caused by the front-end browser, the same-origin policy. The "protocol/host (domain name)/port tuple" of the two URLs is the same, that is, the same source.

React App runs on native port 3000

2. Solution:

1. cors: background server-side solution

//Take Node server as an example
const express = require("express");

const cors = require("cors")

const app = express();

// Allow cross-domain
// Access-Control-Allow-Origin: *

app.use(cors())

2. jsonp

Need to use plug-in: fetch-jsonp (if using Fetch request, use the plug-in)
Steps for usage:

1. Download: `npm i fetch-jsonp`

   2. Introduce into the page
      `import fetchJsonp from'fetch-jsonp'`

   3. Use

      ```js
      // Introduce fetchJsonp
      import fetchJsonp from "fetch-jsonp"

      fetchJsonp("http://localhost:3005/news?type='International News'")
        .then(res=>res.json())
        .then(res=>{console.log(res)})
      ```

      Backend needs to support `jsonp`, express only needs `res.jsonp()`

      ```js
      //Node
      // JSONP interface
      app.get("/news", (req,res) => {
          res.jsonp({
              type: req.query.type,
              list: [{
                  id: 1,
                  title: "xxx news"
              }]
          })
      })
      ```

3. Proxy

  • Let the background request the background, there is no cross-domain problem
  • There is no cross-domain problem in the specified location of the front desk request
  • React has two forms to implement proxy

method 1

Add the following configuration to package.json

"proxy":"http://localhost:5000"

illustrate:

  1. Advantages: Simple configuration, no prefix can be added when the front-end requests resources.
  2. Disadvantage: Multiple agents cannot be configured.
  3. Working mode: Configure the proxy in the above way. When a resource that does not exist in 3000 is requested, the request will be forwarded to 5000 (matching front-end resources first)

Method 2

Step 1: Create an agent configuration file

Create a configuration file under src: src/setupProxy.js

Write setupProxy.js to configure specific proxy rules:

const proxy = require('http-proxy-middleware')

module.exports = function(app) {
   app.use(
     proxy('/api1', {//api1 is the request that needs to be forwarded (all requests with the prefix /api1 will be forwarded to 5000)
       target:'http://localhost:5000', //Configure forwarding target address (server address that can return data)
       changeOrigin: true, //Control the value of the host field in the request header received by the server
       /*
       When changeOrigin is set to true, the host in the request header received by the server is: localhost:5000
       When changeOrigin is set to false, the host in the request header received by the server is: localhost:3000
       The default value of changeOrigin is false, but we generally set the value of changeOrigin to true
       */
       pathRewrite: {'^/api1':''} //Remove the request prefix to ensure that the normal request address is delivered to the background server (must be configured)
     }),
     proxy('/api2', {
       target:'http://localhost:5001',
       changeOrigin: true,
       pathRewrite: {'^/api2':''}
     })
   )
}

illustrate:

  • Advantages: You can configure multiple agents, and you can flexibly control whether the request goes through the agent.
  • Disadvantages: The configuration is cumbersome, and the front end must add a prefix when requesting resources.

Request writing
The proxy name of the middleware configuration (/api) + the real interface address


    // proxy proxy, setupProxy.js
    //Add proxy path /api
    proxyFun2(){
        fetch("/api1/user/3120180905406").then(res => res.json()).then(res => {
            console.log(res);
        })
    }
created at:11-12-2021
edited at: 11-12-2021: