gpt4 book ai didi

javascript - 如何访问函数中的命名参数?

转载 作者:行者123 更新时间:2023-12-02 18:10:35 27 4
gpt4 key购买 nike

我正在使用 Node JS 开发一个 REST Web 服务,以便与 Backbone JS 结合使用。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

关于javascript - 如何访问函数中的命名参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19740475/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com