reactjs中配置代理跨域

第一步,下载依赖 http-proxy-middleware

yarn add http-proxy-middleware

第二步,在src下建立setupProxy.js

const proxy = require('http-proxy-middleware')

module.exports = function(app) {
  app.use(proxy('/api', { 
       target: "https://h5api.zhefengle.cn",
       secure: false,
       changeOrigin: true,
       pathRewrite: {
        "^/api": "/"
       },
    })
  );
};

注意:https://h5api.zhefengle.cn 这个是一个开源的接口,开源加入项目直接测试

第三步,在数据请求中直接请求,在真实url后添加/api即可,eg

const login=()=>{
    return Api("/api/index/index_tab.html?",'GET')
}

亲测有效

原文地址:https://www.cnblogs.com/ldlx-mars/p/11164598.html