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 $_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?
Getting Any URL Parameter
For this example, we'll grab a parameter directly from the URL.
Let's say we are using the example URL:
http://example.com/api/users/?id=4&token=sdfa3&geo=us
The parameters that come out of this will be:
id 4
token sdfa3
geo us
It's very easy to grab these parameters. Here's the route and the method for grabbing parameters is
req.param()
.// routes will go here
The parameters are naturally passed through the req (request) part.
Now if we go to our browser at
http://localhost:8080/api/users/?id=4&token=sdfa3&geo=us
we'll be able to see the three parameters!
UPDATE 4 May 2014
Old answer preserved here: https://gist.github.com/stefek99/b10ed037d2a4a323d638
1) Install express:
npm install express
app.js
2) Run the app:
node app.js
3) Visit in the browser:
http://localhost:3000/endpoint?id=something
(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
parse.js
, and run it on the console by entering "node parse.js".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
http://localhost:8080/?name=abel&fruit=apple
in your browser, and you will get a cool response based on the code.You can use
You can use with express ^4.15.4:
Hope this helps.