Query String Express.js routes


Query strings in Express.js routes are used to pass data to the server via the URL. Unlike route parameters, which are part of the path, query strings are appended to the end of the URL after a question mark (?) and are used to pass additional data or options.

How Query Strings Work

Query strings follow the ? symbol in the URL and are composed of key-value pairs separated by &. For example, in the URL /search?term=express&page=2, the query string is term=express&page=2.

Accessing Query Strings

In Express.js, query strings are accessible via the req.query object. Each key in the query string corresponds to a property in the req.query object.

Example:

const express = require('express'); const app = express(); // Route that uses query strings app.get('/search', (req, res) => { const term = req.query.term; // Access query parameter 'term' const page = req.query.page; // Access query parameter 'page' res.send(`Search term: ${term}, Page: ${page}`); }); app.listen(3000, () => { console.log('Server running on port 3000'); });

In this example:

  • If the URL is /search?term=express&page=2, req.query.term will be 'express', and req.query.page will be '2'.

Using Query Strings

Query strings are often used to filter results, paginate data, or pass additional parameters in a request. They provide a way to send data that doesn't affect the route path but still needs to be processed by the server.

Example of Using Query Strings for Filtering and Pagination:

app.get('/products', (req, res) => { const category = req.query.category; // Filter products by category const page = parseInt(req.query.page) || 1; // Default to page 1 if not provided const limit = parseInt(req.query.limit) || 10; // Default to 10 items per page if not provided // Logic to retrieve products based on filters and pagination res.send(`Category: ${category}, Page: ${page}, Limit: ${limit}`); });

In this example:

  • category filters the products by category.
  • page and limit are used for pagination.

Handling Optional Query Parameters

Query parameters are typically optional. If a parameter is not included in the query string, it will simply be undefined in req.query.

Example:

app.get('/profile', (req, res) => { const userId = req.query.userId; // May be undefined if not provided const showDetails = req.query.showDetails === 'true'; // Convert string to boolean if (userId) { res.send(`User ID: ${userId}, Show details: ${showDetails}`); } else { res.send('No user ID provided'); } });

URL Encoding

Query strings must be URL-encoded, especially if they contain special characters or spaces. This ensures that characters are properly transmitted over the internet

and interpreted correctly by the server. For instance, spaces in query strings should be encoded as %20 or +.

Example of URL Encoding:

If you want to pass a search term with spaces:

/search?term=node.js%20express

Or:

/search?term=node.js+express

In both cases, the server will receive req.query.term as 'node.js express'.

Summary

  • Query Strings: Data appended to the URL after a ?, used to pass additional parameters.
  • Accessing Query Strings: Access via req.query in Express.js.
  • Usage: Common for filtering, sorting, pagination, or passing extra data.
  • Optional Parameters: Query parameters are optional; they will be undefined if not provided.
  • URL Encoding: Ensure special characters and spaces are properly encoded.

Query strings provide a flexible way to send data to the server without changing the URL path, making them useful for a variety of scenarios where additional data needs to be included in a request.