【问题标题】:how do I access a named parameter in a function? [duplicate]如何访问函数中的命名参数? [复制]
【发布时间】:2013-11-02 09:12:47
【问题描述】:

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

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

我在 app.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));
                }
                });
        }
    }
}

【问题讨论】:

  • 你想要什么不清楚,至少对我来说是这样。
  • 感谢您的提醒,我会尽力使其更详细。

标签: javascript node.js rest express


【解决方案1】:
return function(req,res)
   {
      var id = req.params.id;
      console.log("id: "+id);
      // ...  

这应该可以按预期工作。你可以阅读更多here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-11-10
    • 2011-09-26
    • 2014-11-04
    • 2022-01-01
    • 2011-09-29
    • 1970-01-01
    • 2011-11-19
    • 2015-05-04
    相关资源
    最近更新 更多