7

I want to do the following, but I don't know if its possible without do it string manipulation in the URL. I want to get some parameter from the url, I have some data that is passed in the post data, but I need to get some information(userID) from the URL:

  1. I'm using express
  2. I'm using post method
  3. My URL is like:

http://www.mydomain.com/api/user/123456/test?v=1.0

I have the following code, to get all post request:

var http = require('http');
var url = require('url') ;
exp.post('*', function(req, res, next) {
     var queryObject = url.parse(req.url,true).query; // not working only get in the object the value v=1.0
     var parameter = req.param('name'); // get undefined

}

What I'm missing?

Thanks

Boba Fett likes JS
  • 747
  • 3
  • 10
  • 21
  • possible duplicate of [how to get GET (query string) variables in node.js?](http://stackoverflow.com/questions/6912584/how-to-get-get-query-string-variables-in-node-js) – MikeSmithDev Mar 04 '14 at 21:51

1 Answers1

10

GET params (as an object) are located in req.query. Give this a try:

exp.post('*', function(req, res, next) {
  console.log(req.query);
  console.log(req.query.v);
  next();
});

You will have to set up your route differently if you want to grab parameterized slugs from the URL itself. These are located in req.params:

exp.post('api/user/:userid', function(req, res, next) {
  console.log(req.params);
  console.log(req.params.userid);
  next();
});
SamT
  • 10,374
  • 2
  • 31
  • 39
  • 3
    @BobaFettlikesJS Glad to hear it's working! Don't forget to click the check mark next to the answer if you're satisfied ;) – SamT Mar 06 '14 at 17:08
  • @SamT , could you please tell me how to validate 'userid' ? I am facing one problem . suppose my api url is 'api/user/:userid' . when i invoke api without any value for userid , the response returns 404 . Could you please tell me how to validate the parameter ? – Arj 1411 Feb 09 '17 at 07:07
  • http://stackoverflow.com/questions/41933674/uri-parameter-validation-in-mcs-nodejs – Arj 1411 Feb 09 '17 at 07:09