Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Parameter From URL in POST method in NodeJS/Express

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

like image 331
Boba Fett likes JS Avatar asked Mar 04 '14 19:03

Boba Fett likes JS


People also ask

How do you access GET parameters after Express?

We can access these route parameters on our req. params object using the syntax shown below. app. get(/:id, (req, res) => { const id = req.params.id; });

CAN POST request have query parameters?

POST should not have query param. You can implement the service to honor the query param, but this is against REST spec. "Why do you pass it in a query param?" Because, like for GET requests, the query parameters are used to refer to an existing resource.

How do you get variables in Express js in the GET method?

In Express. js, you can directly use the req. query() method to access the string variables.


1 Answers

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();
});
like image 158
SamT Avatar answered Oct 09 '22 06:10

SamT