我遇到了一个长期的问题,那就是Express会分出HTML字符串而不是JSON,而无论如何我们显然都试图强制JSON总是从服务器中出来-
原来这是我的错误处理中间件中的一个问题-我错过了下一个参数,例如:
这是失败的:
app.use(function (err, req, res) {
res.status(err.status || 500).json({
error: 'sorry the API experienced an error serving your priority request'
});
});
这是正确的行为:
app.use(function (err, req, res, next) {
res.status(err.status || 500).json({
error: 'sorry the API experienced an error serving your priority request'
});
});
如您所见,添加第四个参数“ next”使Express可以将其识别为错误处理回调函数。
我的问题是-Express如何知道第四个参数已存在,或者更不用说参数的类型了?我唯一的猜测是Express正在使用Function.prototype.toString()来查看参数的数量。还是他们在做另一种方式?
正如注释中所写 Function.length
length
是函数对象的属性,它指示函数期望多少个参数,即形式参数的数量。
Layer.prototype.handle_error = function handle_error(error, req, res, next) {
var fn = this.handle;
if (fn.length !== 4) {
// not a standard error handler
return next(error);
}
try {
fn(error, req, res, next);
} catch (err) {
next(err);
}
};
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句