noel lee noel lee - 2 months ago 8
Node.js Question

How to get the url parameter?

I am very new to Express, I want to parse the url parameter. My code as below:

router.get('/', function (req, res) {
var aCustomerIdValue = req.param.aa;
console.log('In / Function be called: %s',aCustomerIdValue);
res.redirect('/checkouts/new');
});


But the console show "undefine". Any clue for it?
My express is 4.0.
Thank you in advanced!

rsp rsp
Answer

Parameter types

req.params

It should be req.params.aa instead of req.param.aa - see:

but it would work only for ":aa" parameters in the path of routes like router.get('/:aa', ...) - it would save XXX from request to GET /XXX in req.params.aa

req.query

For query parameters (most likely for GET requests) use req.query - see:

It will save XXX from request to GET /?aa=XXX in req.query.aa

req.body

For the parameters passed in the request body use req.body - see:

It will save aa parameters passed in the body of the request (most likely for POST requests) in req.body.aa

req.param()

There is also req.param('name') for either one of those, searched in order of:

  1. req.params
  2. req.body
  3. req.query

but it is deprecated - thanks to Ben Fortune for pointing it out in the comment - see: http://expressjs.com/en/api.html#req.param

Your example

Try:

router.get('/', function (req, res) {
  var aCustomerIdValue = req.query.aa;
  console.log('In / Function be called: %s', aCustomerIdValue);
  res.redirect('/checkouts/new');
});

if the parameter is passed in the query string, or:

router.get('/', function (req, res) {
  var aCustomerIdValue = req.body.aa;
  console.log('In / Function be called: %s', aCustomerIdValue);
  res.redirect('/checkouts/new');
});

if the parameter is passed in the request body.

Comments