Can we get the variables in the query string in Node.js just like we get them in $_GET
in PHP?
I know that in Node.js we can get the URL in the request. Is there a method to get the query string parameters?
Can we get the variables in the query string in Node.js just like we get them in I know that in Node.js we can get the URL in the request. Is there a method to get the query string parameters? |
||||
|
Yes you can access req.url and parse it manually:
However, in expressjs it's already done for you and you can simply use req.query for that:
|
|||||||||||||||||||||
|
Since you've mentioned Express.js in your tags, here is an Express-specific answer: use req.query. E.g.
|
|||||||||||||||||||||
|
In Express, use
That said, most of the time, you want to get the value of a parameter irrespective of its source. In that case, use The value of the parameter will be returned whether the variable was in the route parameters, query string, or the encoded request body. Side note- if you're aiming to get the intersection of all three types of request parameters (similar to PHP's |
|||||||||||||||||||||
|
For Express.js you want to do
|
|||||||||||||||||||||
|
I learned from the other answers and decided to use this code throughout my site:
Then you can just call
where the URL for get should be
|
|||||||||||||||||||||
|
You should be able to do something like this:
|
|||||
|
UPDATE 4 May 2014 Old answer preserved here: https://gist.github.com/stefek99/b10ed037d2a4a323d638 1) Install express: app.js
2) Run the app: 3) Visit in the browser:
(many things have changed since my answer and I believe it is worth keeping things up to date) |
|||||
|
A small Node.js HTTP server listening on port 9080, parsing GET or POST data and sending it back to the client as part of the response is:
Save it as |
|||||
|
Whitequark responded nicely. But with the current versions of Node.js and Express.js it requires one more line. Make sure to add the 'require http' (second line). I've posted a fuller example here that shows how this call can work. Once running, type
|
||||
|
There are 2 ways to pass parameters via GET method
Method 2 :
General Approach : Passing variables as query string using '?' operator
|
||||
|
It is so simple: Example URL:
You can print all the values of query string by using:
Output
To print specific:
Output
|
||||
|