7

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?

hexacyanide
  • 88,222
  • 31
  • 159
  • 162
Alex Cebotari
  • 291
  • 2
  • 4
  • 9
  • And specifically on that page: http://stackoverflow.com/a/6913287/95190, which is the answer that best fits your needs. – WiredPrairie Sep 26 '13 at 13:45
  • Also, you can use `req.param("userID")` if you don't know where the value might be, but `req.query.userID` is all you'd need. – WiredPrairie Sep 26 '13 at 13:48

1 Answers1

21

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
hexacyanide
  • 88,222
  • 31
  • 159
  • 162
  • Sorry, 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 http://1.2.3.4/status?userID=1234 I receive answer "error": "request is not defined" – Alex Cebotari Sep 26 '13 at 13:31
  • Express has a number of other options that don't require another module (see duplicate answer) – WiredPrairie Sep 26 '13 at 13:47
  • after change request.url to req.url server give me answer: "error": "Cannot call method 'parse' of undefined" – Alex Cebotari Sep 26 '13 at 13:50
  • @AlexCebotari - look at the duplicate post suggested in a comment on your question. And my other comments. You don't need `parse`. – WiredPrairie Sep 26 '13 at 14:11
  • Sorry, 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. – hexacyanide Sep 27 '13 at 00:18