Follow @endyourif rss Facebook LinkedIn

Access query string parameters with Express and Node.js Access query string parameters with Express and Node.js

Published on Feb 15, 2020

Passing data through the URL is a very common practice. As you can see with the URLs on my website, I pass - what I call - a slug of my post title in the URL. In this case: access-query-string-parameters-with-express-and-node-js. With this data I can figure out dynamically what blog post to show. Another common way is to use query string parameters such as ?id=1. There are two common ways that I perform this using Express and Node.js.

If you are not already familiar with Express you can read my article on setting up Express with Node.js before you dive into this blog.

Using req.params with Express routes

This approach is my personal preference because it leverages strongly named parameters in my Express routes. If you are looking for other Node.js tutorial be sure to check them out as I have written many using more advanced techniques.

Here is an example of how I would access the aforementioned slug in my website:

app.get("/:slug", function(req, res) {
	var slug = req.params.slug;

Any URL on my website that is not the homepage will contain a parameter called slug that I can access using req.params.slug because I named it inside my app.get function definition. From this point I can continue processing and fetch the contents of my article from the database or file; whatever suits your needs.

Using req.query with Node.js

The other method that I commonly use to access query parameters is to use req.query. I previously mentioned that it is common to append something like ?id=1 to the end of the URL. Perhaps I want to access a url such as /post?id=1. I can access the ID query string as follows:

Similar to the slug parameter, using req.query I can also access with an expected variable name (id) which is extremely handy. Just like the req.params approach I can take the ID and use it to fetch the data from my database.

If you are just starting with Express, one of the most common errors that you will often see is cannot set headers after they are sent to the client. Have no fear though, I describe the 3 most common reasons for this problem with clear examples to fix your problem.

Tags: Node js Tutorial | express

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP