首页 > 解决方案 > Fetch API 没有收到 Express 错误 JSON?

问题描述

我已经构建了一个简单的 REST api,现在我正在尝试将前端客户端连接到它。作为我的错误处理过程的一部分,我想将任何服务器端错误作为 JSON 对象发送到我的客户端,以便我可以为用户显示适当的错误消息。

我的后端快递代码示例:

try {
    const newPost = new Post({
      title: req.body.title,
      body: req.body.body,
      author: author._id,
    });
    await newPost.save();
    res.json(newPost);
  } catch (err) {
    console.log(err);
    res.status(400).json({ err });
  }

测试时,如果后验证失败,我的块中的 The console.log(err)in my catchblock 会打印出一个错误对象,例如

errors: {
    title: ValidatorError: Path `title` is required.
...
}

这是我如何从前端客户端与 API 进行通信的示例。

fetch(url, options)
    .then((res) => {
      console.log(res);
      if (res.status !== 200) throw new Error(res);
      return res.json();
    })
    .then((data) => console.log(data))
    .catch((err) => console.log(err));
};

console.logres 拾取以下对象:

body: ReadableStream
   locked: false
bodyUsed: false
headers: Headers {}
ok: false
redirected: false
status: 400
statusText: "Bad Request"
type: "basic"
url: "http://localhost:3001/posts"

尽管我的后端发出了 a json(err),但这似乎并没有在上述响应中得到体现。那么如何才能获取fetch从后端发送的错误对象呢?

标签: javascriptnode.jsexpressfetch-api

解决方案


推荐阅读