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:
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
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; });
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.
In Express. js, you can directly use the req. query() method to access the string variables.
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With