【发布时间】:2019-01-22 15:55:47
【问题描述】:
我正在尝试编写一个中间件来处理错误。但我无法弄清楚如何将正确的格式发送到我的前端。下面我将列出我所有的尝试,希望能帮助你。
尝试 1
app.use(function(err, req, res, next) {
const formatted = err;
res.send(formatted)
});
导致邮递员
{ “代码”:422 }
尝试 2
app.use(function(err, req, res, next) {
const formatted = `${err}`;
res.send(formatted)
});
结果(邮递员)
错误:请求返回错误代码:422 和正文:{"status":422,"title":"显示名称:build_id 已在此产品上使用。","type":"https://developer.bigcommerce.com/api#api-status-codes" ,"errors":{"display_name":"显示名称:build_id 已在此产品上使用。"}}
这是我想要的数据,但我需要它在 json 中
问题为什么字符串插值后显示的数据更多?如何将其格式化为 json?
【问题讨论】:
-
我查看了所有这些答案。我需要别的东西。
-
console.log()的错误不是 JSON,而是文本。我认为您的错误与消息中返回的 bigcommerce 有关 -
为什么是文字?我知道 API res(当我在邮递员中尝试时)返回 json... 将其转换为某处的文本
-
Error: Request returned error code: 422 and body: {"status":422,"title":"The display name: build_id has already been used on this product.","type":"https://developer.bigcommerce.com/api#api-status-codes","errors":{"display_name":"The display name: build_id has already been used on this product."}}console 遇到的问题,即The display name: build_id has already been used on this product.
标签: javascript node.js express