cr0 所描述的方法可能是“正确的方法”。我不知道这种较新的辅助方法。
该解决方案是正确的。您可以使用req.get 以不区分大小写的方式获取标头,并使用正则表达式检查值。通常我使用以下内容。
module.exports = function() {
function(req, res, next) {
if(req.get("accept").match(/application\/json/) === null) {
return res.redirect(406, "/other/location");
};
next();
}
}
那么这可以作为中间件使用。
app.use(require("./jsonCheck")());
您还可以通过更改导出的函数来更详细地使用模块并重定向到自定义位置。
module.exports = function(location) {
function(req, res, next) {
if(req.get("accept").match(/application\/json/) === null) {
return res.redirect(406, location);
};
next();
}
}
并像这样使用它
app.use(require("./jsonRedirect")("/some.html"));