Joseph Chien
Joseph Chien

Reputation: 47

How to get params in URL with Node.js

I followed a tutorial online that taught me how to create a form and display the user input.

However, I would like to know how can I GET the params in a URL.

For example, with the following URL "http://localhost:8181?fname=joseph&gender=male", how do I GET the fname and gender and display it?

Or even more, how is the whole thing set up? In my understanding, node.js creates a local server to display a website.

I tried research on express and request, but I still can't find anything and my understanding on node.js is terrible too. Thanks in advance!

Upvotes: 1

Views: 9642

Answers (1)

ahwayakchih
ahwayakchih

Reputation: 2371

You mentioned express, but did you check their documentation? Express provides req.query (http://expressjs.com/en/api.html#req.query), so your variables should be accessible through req.query.fname and req.query.gender.

If you're trying to get variables using "vanilla" node.js, request object has req.url. You can parse it using built-in url module (https://nodejs.org/dist/latest-v6.x/docs/api/url.html):

var parsedURL = url.parse(req.url, true);

After that, you will be able to access variables just like with express example above.

Upvotes: 4

Related Questions