How to pass parameter to routes?

故事扮演 提交于 2019-12-11 06:06:32

问题


I am using Nodejs .

Server.js

app.get('/dashboard/:id', routes.dashboard);

Routes / index.js

exports.dashboard = function(req, res){


}

I want to be able to pass the 'id' variable from app.js to the dashboard function . How do I go about doing this ?


回答1:


Assuming ExpressJS, you shouldn't need to pass it.

For each parameter placeholder (like :id), req.params should have a matching property holding the value:

exports.dashboard = function (req, res) {
    console.log(req.params.id);
};

Though, this assumes the requested URL matches the route by verb and pattern.




回答2:


Just ensure that your GET call from the client is something like this: /dashboard/12345. 12345 is the id you want to pass to dashboard.

So, you can access it like this in server:

exports.dashboard = function(req, res){
  var id = req.params.id;
  console.log('ID in dashboard: %s', id);
}


来源:https://stackoverflow.com/questions/17398766/how-to-pass-parameter-to-routes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!