当 http 响应状态为 400 时使用 fetch api 获取自定义错误消息

Getting custom error message using fetch api when http response status is 400

我有 Python Flask (v 1.0.0) 后端,returns 状态为 400 的 http 响应和自定义错误消息

return Response('My custom errror message', 400)

在我的前端,我使用 Fetch API:

对后端进行了 API 调用
fetch(url, options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(error => console.log(error));

由于 400 是 BAD REQUESTfetch 直接转到 catch,而我只有 TypeError: Failed to fetch 消息。

如何在前端获取我的自定义错误消息而不是 Failed to fetch 消息?它在 DevTools 中可见,所以我希望它应该以某种方式在 fetch 中可用?

如果状态超出 200-299 范围,Fetch 不会抛出异常。您正在尝试将纯文本 ("My custom error message") 解析为 json,这就是异常的原因。您必须在调用 json()

之前检查 response.status

原来是nginx配置问题。当我说当响应为 400 时获取直接进入 .catch 时,我是对的,但原因是请求实际上失败了——我在控制台中看到了 CORS 错误。 将 always 参数添加到我的 nginx 配置后,不再有 CORS 错误,我可以在 .then 中访问 My custom error message,它不再直接进入 .catch。 此处有更多详细信息:nginx add headers when returning 400 codes