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

Mar*_*s B 5 javascript http fetch-api

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

return Response('My custom errror message', 400)
Run Code Online (Sandbox Code Playgroud)

在我的前端,我使用 Fetch API 对后端进行了 API 调用:

fetch(url, options)
  .then(response => response.json())
  .then(response => console.log(response))
  .catch(error => console.log(error));
Run Code Online (Sandbox Code Playgroud)

由于 400 是一个BAD REQUESTfetch直接进入catch,我所拥有的只是TypeError: Failed to fetch消息。

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

在此处输入图片说明在此处输入图片说明

Mar*_*s B 2

原来是nginx配置问题。当我说当.catch响应为 400 时 fetch 会直接进入时,我是对的,但原因是请求实际上失败了 - 我在控制台中看到 CORS 错误。将参数添加到我的 nginx 配置后always,不再出现 CORS 错误,我可以访问My custom error message内部.then,并且不再直接访问.catch. 更多详细信息请参见:nginx add headers when returned 400 code