react配置代理,解决跨域

方案1

//配置: package.json
"proxy":"https://xxxx.com"

问题: 只能代理一个服务器

方案二

利用客户端代理中间件(http-proxy-middleware)完成,

官网给了新的使用方式,在src下新建文件setupProxy.js加下面代码,

无需单独应用,webpack会自动引入文件。

npm install http-proxy-middleware -S

文件内容

//verion < 1.0版本
const proxy = require('http-proxy-middleware'); //需要安装中间件  
module.exports = function(app) {
  app.use(
    proxy("/api", {
      target: 'https://xxx.com',
      changeOrigin: true
    })
  );
  app.use(
    proxy("/v2", {
      target: "https://xxx2.com",
      changeOrigin: true
    })
  );
};

//组件: /api/xx ... | /v2/...

//verion > 1.0
const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {

  app.use('/api', createProxyMiddleware({
    target: 'http://localhost:3000',
    changeOrigin: true,
  }));

  app.use('/api2', createProxyMiddleware({
    target: 'http://xxx.com',
    changeOrigin: true,
    pathRewrite: { //路径替换
      '^/api2': '/api', // axios 访问/api2 == target + /api
    }
  }));

};

方案三

配置create-react-app环境下的webpack

无需安装中间件

修改eject后的config目录下的webpackDevServer.js配置文件

// config/webpackDevServer.js

proxy: {
  '/api2': {
    target: 'http://xxx.com', // 后台服务地址以及端口号
    ws: true, // websoket 服务
    changeOrigin: true, //是否跨域
    pathRewrite: { '^/api2': '/api' }
  }
}
原文地址:https://www.cnblogs.com/anin/p/13558961.html