Home > Article > Web Front-end > How to solve cross-react domain issues
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.
Solution to react cross-domain problem:
1. The simplest operation
Add "proxy": "http://localhost:8000"
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-middlewarenpm i http-proxy-middleware --saveCreate src/setupProxy.jsconst 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!