多种解决react中跨域问题方案
在网上看到了多种解决react跨域的方法,但是在实际的项目中并不是所有的方法都是可行的。
一、最简单的操作
在package.json中加入
"proxy": "http://localhost:8000"
然后你页面中的请求fetch('/api/userdata/')就会转发到proxy中的地址
也就是真实的请求是http://0.0.2.89:7300/api/userdata/,而且也不会有跨域问题
因为在浏览器看来,你只是发了fetch('/api/userdata/'),没有跨域问题
二、添加多个代理
在package.json中加入
"proxy": {
   "/api": {
     "target": "http://localhost:8000",
     "changeOrgin": true
   },
    "/app": {
     "target": "http://localhost:8001",
     "changeOrgin": true
   }
},
使用方法
axios.post('/api/users').then(res =>{
    console.log(res)
})
但是当重新执行npm start时会报错,说"proxy"的值应该是一个字符串类型,而不能是Object。
其原因是由于react-scripts模块的版本过高,需要删除到原目录下node_modules中的react-scripts文件夹,安装低版本
npm install react-script@1.1.1 --save
的确跨域问题可以解决了,但是又出现了新的问题,我在项目中使用了sass,当把react-scripts改为低版本后并不支持对sass的解析,如果要想支持sass的话,需要到 node_modules/react-scripts/config中进行配置,但是并不推荐你这样做。
三、最佳推荐
下载 http-proxy-middleware
npm i http-proxy-middleware --save
创建 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
      }
    })
  )
}
 
    
    
    
