我想根据一些req.headers数据输出HTML或JSON。例如:如果req.headers.contentType ==“application / json”,我将返回JSON,否则返回HTML。
var route = {
html: function(req, res, next) {},
json: function(req, res, next) {}
}
app.get('/test', route);
这显然不起作用。所以我想我需要一个中介功能:
app.get('/test', _findRoute);
function _findRoute(req, res, next) {
if(req.headers["content-type"] === "application/json") {
return route.json;
} else {
return route.html;
}
}
这显然也行不通,因为此时我实际上无法访问路由对象。
我能做到:
app.get('/text', _findRoute(route));
但后来我无法访问req对象。
我实际上不知道如何继续,所以任何想法都非常受欢迎:)
答案 0 :(得分:3)
如果您只重写_findRoute,那么最后一个版本(app.get('/text', _findRoute(route));
)将起作用。
function _findRoute (route) {
return function (req, res, next) {
if(req.headers["content-type"] === "application/json") {
route.json(req, res, next);
}
else {
route.html(req, res, next);
}
}
}