React Native开发React Native开发经验集React生态圈

react 跨域问题解决

2019-12-19  本文已影响0人  知足常乐晨

create-react-app工程跨域
package.json文件中增加如下配置:

"proxy": "http://localhost"  // 配置你要请求的服务器地址

若只配置一个地址上面写法就可以,若想配置多个代理,就需要写成如下格式:


...
  "proxy": {
    "/data": {
      "target": "http://localhost",
      "changeOrigin": true
    },
    "/rest": {
      "target": "http://localhost/rest",
      "changeOrigin": true
    }
  }
...

重新启动后报错:


image.png

错误提示:只支持string类型,不支持object

原因:
create-react-app 的版本低于 2.0 的时候可以在 package.json 增加 proxy 配置, proxy可以是object类型,
create-react-app 的版本高于 2.0 版本的时候在 package.json 只能配置 string 类型.

解决方法:

安装http-proxy-middleware

yarn add http-proxy-middleware

在src/下新建setupProxy.js

const proxy = require("http-proxy-middleware");

module.exports = function (app) {
    app.use(proxy("/data", {
        target: "http://localhost", //配置你要请求的服务器地址
        pathRewrite: {'^/data': ''},
        changeOrigin: true,
    }))
    app.use(proxy("/rest", {
        target: "http://localhost/rest",
        pathRewrite: {'^/data': ''},
        changeOrigin: true,
    }))
};

使用的时候直接路径以'/data'或者'/rest'开头即可

参考文献:
React跨域设置,一分钟解决跨域问题

上一篇 下一篇

猜你喜欢

热点阅读