gpt4 book ai didi

node.js - ExpressJS 4.15.2 自定义中间件设置内容类型

转载 作者:太空宇宙 更新时间:2023-11-04 00:25:04 25 4
gpt4 key购买 nike

我有一小块自定义中间件,但我似乎无法获得除 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com