This question already has answers here:
Using multiple parameters in URL in express
                            
                                (2个答案)
                            
                    
                6年前关闭。
        

    

我正在开发使用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));
                }
                });
        }
    }
}

最佳答案

return function(req,res)
   {
      var id = req.params.id;
      console.log("id: "+id);
      // ...


这应该可以正常工作。您可以阅读更多here

10-06 07:43
查看更多