我正在构建一个Web应用程序,其中对服务器的大多数请求需要进行标识符 - 数据对象映射。我想覆盖像这样处理请求的任何地方,但我不想为每个请求写mapping
,有更好的方法吗?
var express = require("express");
var app = express();
function mapping(req,res,next){
console.log(req.params);
// actual data fetch from server depending on req.params
// Example, if req.params.userid defined -> fetch userid from db and place it
if ( req.params.userid){
req.user = {
name: "Mustafa",
title: "Student"
}
}
next();
}
app.get("/:userid", mapping, function(req,res){
res.send(req.user);
});
app.listen(3000);
答案 0 :(得分:3)
您可以使用app.param
将中间件专门应用于存在userid
的路由:
function mapping(req,res,next,userId){
console.log(req.params);
// actual data fetch from server depending on req.params
// Example, if req.params.userid defined -> fetch userid from db and place it
if (userid){
req.user = {
name: "Mustafa",
title: "Student"
}
}
next();
}
app.param( "userid", mapping );
app.get("/:userid", function(req,res){
res.send(req.user);
});
答案 1 :(得分:2)
您只需要app.use()
映射。因为它总是调用next(),所以一旦完成它就会推迟到下一个路径。
// always use 'mapping' middleware.
app.use(mapping);
// handle GET /{userid}
app.get("/:userid", function(req,res){
res.send(req.user);
});