Nodejs,Express在开始时获取请求参数

时间:2014-08-11 19:39:11

标签: node.js http express request

我正在构建一个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);

2 个答案:

答案 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);
});