react配置了setupProxy却仍无法跨域?

const { createProxyMiddleware } = require('http-proxy-middleware')

module.exports = function (app) {
    app.use('/api',    // 指定需要转发的请求
        createProxyMiddleware({
            target: 'http://localhost:7001',
            changeOrigin: true,
            pathRewrite(path) {
                return path.replace('/api', '/');
            }
        })
    );
}

image.png

阅读 11.9k
6 个回答

跨域可不是报的这个错,404,检查你的/api是不是确实需要重写为空

这已经不是跨域的问题了,这是你的接口的地址不对,path重写得这么写吧

path.replace('/api', '');

你上面的写法:
你访问http://localhost:3000/api/login根据你得代理编写规则其实访问的是http://localhost:7001//login,所以就会404了

新手上路,请多包涵

我也遇到这个问题了,未解决

我也遇到这个问题了,未解决,而且请求的IP和端口都没有变!好像没有采用代理配置image.png

我觉得问题应该出在你baseUrl上(我用的是axios)。如果你用了替换规则的话会将原来的
/api--》变为空字符串--》http://xxxx.xxxx.com/。这样就是同域名了。

  export const baseURL = () => {
    if (process.env.VUE_APP_MODE === "development") {
      return "/api"; // baseUrl要改为/api
    }
  };
  devServer: {
    historyApiFallback: true,
    hot: true,
    proxy: {
      "/api": {
        target: "http://xxxx.xxxx.com/",
        secure: false,
        changeOrigin: true,
        logLevel: "debug",
        pathRewrite: { "^/api": "" },
      },
    },
  },
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题