React跨域请求

  1. 在package.json文件中配置proxy信息
    React 2.0及以下的版本:
"proxy": "http://服务器地址"  // 配置你要请求的服务器地址

新版本支持配置多个代理

"proxy": {
    "/path1": {
      "target": "http://服务器地址01",
      "changeOrigin": true
    },
    "/path2": {
      "target": "http://服务器地址02",
      "changeOrigin": true
    }
  }
  1. 使用http-proxy-middleware
const proxy = require("http-proxy-middleware");

module.exports = function (app) {
    app.use(proxy("/data", {
        target: "http://服务器地址1", //配置你要请求的服务器地址
        pathRewrite: {'^/data': ''},
        changeOrigin: true,
    }))
    app.use(proxy("/rest", {
        target: "http://服务器地址2",
        pathRewrite: {'^/data': ''},
        changeOrigin: true,
    }))
};
  1. 在webpack.dev.conf.js中的devServer项进行配置,webpack文件默认是看不到的
devServer: { // 配置webpack-dev-server, 在本地启动一个服务器运行
    contentBase: "./build", //本地服务器所加载的页面所在的目录
    historyApiFallback: true, //不跳转
    port: 8888, //设置默认监听端口,如果省略,默认为”8080“
    inline: true, //实时刷新
    open: true, // 自动打开页面
    historyApiFallback: true,
    proxy: {
      "/path": {
        "target": "https://服务器地址",
        "changeOrigin": true
        }
     }
  },

2020-03-05

posted @ 2020-10-09 16:29  FirstLetterZ  阅读(344)  评论(0)    收藏  举报