javascript - 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 catch
block 会打印出一个错误对象,例如
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.log
res 拾取以下对象:
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
从后端发送的错误对象呢?
解决方案
推荐阅读
- java - Android:从不同的布局到达按钮对象
- javascript - 画布触控支持,定位触控事件
- python - 熊猫找到价格变化一定量所需的最短时间
- jenkins - 为什么我的 Jenkins 管道失败并显示错误代码 24
- mysql - MySQL:使用来自另一个表列的随机值触发更新
- reactjs - how to use spyOn on a class less component
- java - 使用 Intent 从 WebView 拨打电话不起作用
- c++ - std::unordered_map find() 操作在 GCC7 中不起作用
- python - 选择具有 notna 属性的多个 comumns
- python - Python并发第一个结果结束等待尚未完成的结果