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

ReactJS中http-proxy-middleware请求头无法正确设置的问题问询

如何在http-proxy-middleware中实际修改请求头?

为解决CORS错误,我使用http-proxy-middleware模块搭建了本地代理。除了将请求模式设置为"no-cors"外,我还需要修改Content-Type请求头,但这似乎不起作用。实际上,我甚至无法修改经代理转发的请求的响应头——对于本地请求(如获取页面等),我可以修改响应头,但即便如此也无法修改请求头。

我的setupProxy.js代码

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

module.exports = function (app) {
  app.use((req, res, next) => {
    req.header("Content-Type", "application/json");
    res.header("Access-Control-Allow-Origin", "*");
    next();
  });

  function onProxyReq(proxyReq, req, res) {
    console.log("test 1");
    proxyReq.setHeader("Content-Type", "application/json");
    req.header("Content-Type", "application/json");
  }

  app.use(
    "/api",
    createProxyMiddleware({
      target: "https://my-domain.com/",
      changeOrigin: true,
      onProxyReg: { onProxyReq },
      // secure: true,
      // on: {
      //   proxyReq: requestInterceptor(async (buffer, proxyReq, req, res) => {
      //     console.log("test 2");
      //   }),
      // },
      logger: console,
    })
  );
};

发送请求的代码

try {
  let requestOptions: RequestInit = {
    method: "POST",
    mode: "no-cors",
    headers: {
      accept: "application/json",
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      email: { username },
      password: { password },
    }),
  };

  fetch("https://localhost:3000/api/path/to/login/api", requestOptions)
    .then(async function (response) {
      console.log(response);
      if (!response.ok) {
        setError("Error code: " + response.status.toString());
      }
      return response.json();
    })
    .then(function (response) {
      console.log(response);
    });
} catch (e) {
  console.log(e);
}

遇到的错误

Content type 'text/plain;charset=UTF-8' not supported

用Chrome开发者工具查看请求时,请求头确实被设置为text/plain;charset=UTF-8。我尝试将响应头的Content-Type设置为text/plain,但也没有生效,实在搞不懂代理转发后怎么会出现这种情况。

后续排查记录

  • 编辑1:发现部分问题根源——在fetch请求中设置mode: "no-cors"会修改请求头。但这仍然无法解释为什么我的代理无法编辑请求头。当我移除"no-cors"模式,手动复制它生成的请求头发送时,服务器返回400错误(请求无效),明明已经手动复制了所有请求头,服务器收到的请求却和之前不一样,这让我很困惑。
  • 编辑2:移除mode: "no-cors"并手动将Sec-Fetch-Mode请求头设置为"no-cors"时,实际请求中的该头仍然是"cors"!
  • 编辑3:尝试通过ReqBin发送请求,请求成功了!至少可以确认我的请求本身是正确的。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:20:34