Open In App

Difference between req.query and req.params in Express

In this article, we will learn about the req.query and req.params and we will also learn the difference between them.

req.query: Dealing with URL Stuff:

Example: using req.query:




app.get('/search', (req, res) => {
const searchTerm = req.query.query;
// Do something with the search term
});

req.params: Figuring Out Route Things:

Example: using req.params:






// Example of using req.params
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
// Fetch info based on the user ID
});

Difference between req.query and req.params in Express:

Aspect

req.query

req.params

Source of Data

Extra bits at the end of a URL (e.g., form inputs, search bar)

Changing parts in the URL marked by colons

Example URL

‘/search?q=example’

‘/users/:id’

Usage

Ideal for handling URL parameters, especially with search terms

Useful when dealing with dynamic values within a consistent URL structure

Express.js Example

‘javascript app.get(‘/search’, (req, res) => { const searchTerm = req.query.q; // Process search term });

`javascript app.get(‘/users/:id’, (req, res) => { const userId = req.params.id; // Fetch user details based on dynamic user ID });

Scenario Example

Handling a search feature on a website

Accessing user-specific information on a page

Steps to Setup Backend with Node.js and Express:

Step 1: Creating express app:

npm init -y

Step 2: Installing the required packages

npm install express

Example: Create a file named server.js and add the following code:




const express = require('express');
const app = express();
const PORT = 3000;
 
// Route using req.query
app.get('/search',
    (req, res) => {
        const searchTerm =
            req.query.q || 'No search term provided';
        res.send(`Search Term: ${searchTerm}`);
    });
 
// Route using req.params
app.get('/users/:id',
    (req, res) => {
        const userId =
            req.params.id || 'No user ID provided';
        res.send(`User ID: ${userId}`);
    });
 
// Start the server
app.listen(PORT,
    () => {
        console.log(`Server is running at http://localhost:${PORT}`);
    });

Steps to run the App:

node server.js

Ouput for req.params:

Response when we send params

Ouput for req.query:

Response when we send query params

Conclusion:

To keep it simple, req.query deals with data from the end of a URL, while req.params grabs values from dynamic parts of the URL. Whether you’re dealing with a search form or creating web pages with changing parts, knowing when to use each makes Express.js a lot less confusing.


Article Tags :