我有一小块自定义中间件,但我似乎无法获得除 text/html 之外的任何内容类型的响应。
getValidator: function(req, res, next) {
res.setHeader('Content-Type', 'application/json');
if (!req.query.Name) { next('please provide a Name'); }
return next();
}
这是一个 super 小的应用程序,没有其他自定义中间件。
谢谢!
最佳答案
我自己来回答吧。 :) 如果我不正确,请纠正我,但这似乎确实有效。
getValidator: function(req, res, next) {
if (!req.query.Name) { return res.status(500).json({ error: 'please provide a Name' }); }
return next();
}
如果您不使用“返回”,它将继续遍历该链。如果您使用 next('ANYTHING') ,它将触发 ExpressJS 的默认 404 处理程序并尝试返回文本/html。我希望这对某人有帮助! (或者下次我搞砸的时候我)
关于node.js - ExpressJS 4.15.2 自定义中间件设置内容类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43077161/