美文网首页
React跨域请求

React跨域请求

作者: 周_0717 | 来源:发表于2020-03-12 18:32 被阅读0次
    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

    相关文章

      网友评论

          本文标题:React跨域请求

          本文链接:https://www.haomeiwen.com/subject/znwqrhtx.html