如何访问函数中的命名参数

how do I access a named parameter in a function?

本文关键字:参数 函数 何访问 访问      更新时间:2023-09-26

我正在使用Node JS开发一个REST Web服务,以便与Backbone JS结合使用。其中一个 REST 方法是 GET /users/id/:id ,其中 :id 是用户的 id 号。此方法将从数据库返回用户的详细信息。

我不明白的是如何将 :id 参数从 url 传递给响应处理程序。

我已经在应用程序中定义了响应处理程序.js如下所示:

app.get('users/id/:id',user.fetch(db));

这是 user.fetch 函数

exports.fetch = function(db){
    return function(req,res){
        var id = ;//how do I get the Id from the request?
        console.log("id: "+id);
        if(id !== null){
            peopleDb = db.get('people');
            peopleDb.find({"_id":id},function(e,docs){
                if(e){
                console.log(e);
                }else
                {
                    res.setHeader('Content-Type','application/json');
                    res.setHeader('Access-Control-Allow-Origin','*');
                    res.setHeader('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
                    res.writeHead(200);
                    res.end(JSON.stringify(docs));
                }
                });
        }
    }
}
return function(req,res)
   {
      var id = req.params.id;
      console.log("id: "+id);
      // ...  

这应该按预期工作。您可以在此处阅读更多内容