新版react16.6中 create-react-app升级版(webpack4.0) 配置http请求跨域问题

在create-react-app之前的版本,我们配置http请求跨域是直接在package.json配置即可,如下图:

技术分享图片

 

但在最新的create-react-app v2升级版(webpack4.0)中,如果proxy不是字符串,并不能这么在 package.json直接配置,会报错!

通过查阅create-react-app的官方文档https://facebook.github.io/create-react-app/docs/getting-started,找到了如下的解决方案。

     1):安装http-proxy-middleware管理包,cnpm http-proxy-middleware --save

   2):在项目目录src/下新建setupProxy.js文件,然后写入如下代码:

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

module.exports = function(app) {
  app.use(proxy(‘/api‘, { 
       target: ‘http://192.168.1.144:8181‘ ,
       secure: false,
       changeOrigin: true,
       pathRewrite: {
        "^/api": "/"
       },
       // cookieDomainRewrite: "http://localhost:3000"
    }));
};

 

     3): 在组件中使用axios测试http请求是否成功

   

   componentDidMount() {
        axios({
            url: "/api/dataServicePlatform/data/platform?method=select&serviceId=xhly_ChaSight&backtype=json",
            method: "get"
        }).then(res => {
            console.log(res);
        })
    }

   4):  浏览器中成功拿到后端的数据

技术分享图片

 

文章来自:https://www.cnblogs.com/reactjs/p/9988095.html
© 2021 jiaocheng.bubufx.com  联系我们
ICP备案:鲁ICP备09046678号-3