node.js http get request parameters
32,272
You just parse the request URL with the native module.
var url = require('url');
app.get('/status', function(req, res) {
var parts = url.parse(req.url, true);
var query = parts.query;
})
You will get something like this:
query: { userID: '1234' }
Edit: Since you're using Express, query strings are automatically parsed.
req.query.userID
// returns 1234
Author by
Alex Cebotari
Updated on November 27, 2020Comments
-
Alex Cebotari over 3 years
I want to handle an HTTP request like this:
GET http://1.2.3.4/status?userID=1234
But I can't extract the parameter
userID
from it. I am using Express, but it's not helping me. For example, when I write something like the following, it doesn't work:app.get('/status?userID=1234', function(req, res) { // ... })
I would like to have possibility to take value
1234
for any local parameter, for example,user=userID
. How can I do this? -
Alex Cebotari over 10 yearsSorry, may be I not understand how it really work but if I have this code var url = require('url'); app.get('/status', function(req, res) { var url = url.parse(request.url, true); var query = url.query; res.send("response: "+query.useriD); }); and send request get 1.2.3.4/status?userID=1234 I receive answer "error": "request is not defined"
-
WiredPrairie over 10 yearsExpress has a number of other options that don't require another module (see duplicate answer)
-
Alex Cebotari over 10 yearsafter change request.url to req.url server give me answer: "error": "Cannot call method 'parse' of undefined"
-
WiredPrairie over 10 years@AlexCebotari - look at the duplicate post suggested in a comment on your question. And my other comments. You don't need
parse
. -
hexacyanide over 10 yearsSorry, the error is due to reassignment of the URL variable since I was in a rush to get to school. And @WiredPrairie, thanks for pointing out that Express already parsed query strings, I had forgotten.