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
//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())
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"
}]
})
})
```
Add the following configuration to package.json
"proxy":"http://localhost:5000"
illustrate:
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:
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);
})
}