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

如何配置NX代理以保留非200状态码的错误响应内容?

问题

我正在使用nx monorepo,代理功能正常,但返回带错误消息的状态码时,前端无法获取到错误内容。请问如何修改代理配置让错误响应正常返回?

相关代码与信息

代理配置

"/api/v1/*": {
  "target": "http://localhost:3000",
  "secure": false,
  "logLevel": "debug",
  "changeOrigin": true
}

Express后端错误返回代码

res.status(401).send(error)

前端收到的响应

{
  type: "basic", 
  url: "http://localhost:4200/api/v1/users", 
  redirected: false, 
  status: 401, ok: false, statusText: "Unauthorized", 
  headers: Headers(7), 
  body: ReadableStream {locked:false}, bodyUsed: false 
}

前端fetch请求代码

fetch("/api/v1/users", {
    method: "GET",
    headers: {
        "Content-type": "application/json",
        Authorization: window.localStorage.getItem("access_token")
    }
})

解决方案

你的代理配置本身没有问题——nx默认代理会转发所有响应(包括错误状态码的响应)。问题出在前端未正确读取响应体内容。

当fetch请求返回ok: false(状态码4xx/5xx)时,需要手动读取响应的body内容,比如调用response.json()或response.text():

修改后的前端fetch代码:

fetch("/api/v1/users", {
    method: "GET",
    headers: {
        "Content-type": "application/json",
        Authorization: window.localStorage.getItem("access_token")
    }
})
.then(response => {
    if (!response.ok) {
        // 读取错误响应体,根据后端返回格式选择json或text
        return response.json().then(errorData => {
            throw new Error(errorData.message || "请求失败");
        });
    }
    return response.json();
})
.then(data => {
    // 处理成功响应
    console.log(data);
})
.catch(error => {
    // 捕获并展示错误信息
    console.error(error.message);
});

如果后端返回的是纯文本错误,将response.json()替换为response.text()即可。

另外,确保后端返回的error是可序列化的对象或字符串,比如:

// 返回结构化错误示例
res.status(401).json({ message: "未授权,请登录" });

如果确实需要调整代理配置(比如确保特定响应头正确传递),可以添加以下配置:

"/api/v1/*": {
  "target": "http://localhost:3000",
  "secure": false,
  "logLevel": "debug",
  "changeOrigin": true,
  "preserveHeaderKeyCase": true,
  "onProxyRes": function(proxyRes, req, res) {
      // 确保错误响应的Content-Type头正确转发
      if (proxyRes.headers['content-type']) {
          res.setHeader('Content-Type', proxyRes.headers['content-type']);
      }
  }
}

但绝大多数情况下,无需修改代理配置,只要前端正确读取错误响应体就能解决问题。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 05:05:32