Home  >  Article  >  Web Front-end  >  How to solve cross-react domain issues

How to solve cross-react domain issues

coldplay.xixi
coldplay.xixiOriginal
2020-11-16 14:24:534527browse

Solution to the react cross-domain problem: First add [proxy": "http://localhost:8000] to [package.json]; then request [fetch('/api/userdata) in the page /')] will be forwarded to the address in the proxy.

How to solve cross-react domain issues

Solution to react cross-domain problem:

1. The simplest operation

Add "proxy": "http://localhost:8000"

## to package.json and then request fetch('/api/userdata in your page /') will be forwarded to the address in the proxy

That is, the real request is http://0.0.2.89:7300/api/userdata/, and there will be no cross-domain problems

Because from the perspective of the browser, you just sent fetch('/api/userdata/'), there is no cross-domain problem

2. Add multiple proxies

Add to package.json

"proxy": {
"/api": {
"target": "http://localhost:8000",
"changeOrgin": true
},
"/app": {
"target": "http://localhost:8001",
"changeOrgin": true
}
},

Usage method

axios.post('/api/users').then(res =>{
console.log(res)
})

But when npm start is re-executed, an error will be reported, saying that the value of "proxy" should be a string type, not Object.

The reason is that the version of the react-scripts module is too high. You need to delete the react-scripts folder in node_modules in the original directory and install a lower version.

npm install react-script@1.1 .1 --save

It is true that the cross-domain problem can be solved, but a new problem has arisen. I used sass in the project. After changing react-scripts to a lower version, sass is not supported. For parsing, if you want to support sass, you need to configure it in node_modules/react-scripts/config, but this is not recommended.

3. Best recommendation

Download http-proxy-middleware

npm i http-proxy-middleware --save

Create src/setupProxy.js

const proxy = require('http-proxy-middleware')
module.exports = function(app) {
// /api 表示代理路径
// target 表示目标服务器的地址
app.use(
proxy('/api', {
// http://localhost:4000/ 地址只是示例,实际地址以项目为准
target: 'http://localhost:4000',
// 跨域时一般都设置该值 为 true
changeOrigin: true,
// 重写接口路由
pathRewrite: {
'^/api': '' // 这样处理后,最终得到的接口路径为: http://localhost:8080/xxx
}
})
)
}

Related free learning recommendations:

JavaScript (video)

The above is the detailed content of How to solve cross-react domain issues. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn