You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中http-proxy-middleware代理失效致404问题求助

代理配置导致404问题的解决方法

你的代理配置未按预期工作的核心原因是:http-proxy-middleware默认会把匹配的路径(/auth)追加到target地址后。当前配置下,请求/auth/login实际被代理到http://localhost:8080/api/v1/auth/auth/login,这与目标地址不符,因此返回404。

以下是两种有效解决方法:

方法一:添加路径重写规则

在代理配置中加入pathRewrite,将匹配到的/auth前缀替换为空字符串,确保路径拼接正确:

const {createProxyMiddleware} = require('http-proxy-middleware')
module.exports = function (app) {
  app.use(
    '/auth',
    createProxyMiddleware({
      target: 'http://localhost:8080/api/v1/auth',
      changeOrigin: true,
      pathRewrite: { '^/auth': '' } // 移除匹配的前缀,修正路径
    })
  );
};

方法二:调整代理的target地址

将target改为http://localhost:8080/api/v1,让匹配的/auth直接追加到其后,形成正确的目标路径:

const {createProxyMiddleware} = require('http-proxy-middleware')
module.exports = function (app) {
  app.use(
    '/auth',
    createProxyMiddleware({
      target: 'http://localhost:8080/api/v1',
      changeOrigin: true
    })
  );
};

另外,你的fetch请求中有两个多余的请求头:Access-Control-Allow-Origin和Access-Control-Allow-Credentials是后端返回的响应头,不需要在前端请求中设置,建议删除以避免潜在问题:

const LOGIN_URL = '/auth/login'    
const login = () => {
    if (validate()) {
        fetch(LOGIN_URL, {
                method: 'POST',
                body: JSON.stringify(formData),
                headers: {
                    'Content-Type': 'application/json'
                },
                credentials: 'include',
            }
        ).then(response => {
            if (response.ok) {
                window.open("/", "_self")
            }
            return response.json()
        })

    }
}

内容的提问来源于stack exchange,提问作者Topinambur

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 13:18:16