June 21, 2024

ExpressJS Query Parameters

In this article we'll see how to use query parameters in ExpressJS web application. Generally, you use route parameters when you want to pass a specific resource like id. For example, http://ROOT_URL/api/user/1, here 1 is the userId. On the other hand, you'll use query parameters when you want to execute some functionality like sorting, filtering, paginating based on the passed query strings.

What is a query parameter

You get query string by adding query parameters to the URL after a question mark (?). These query strings are added in the form of (key, value) pairs.

For example http://ROOT_URL/products?limit=10&page=2, here limit and page are query parameters with value as 10 for limit and 2 for page. From the URL itself it is clear that you are using pagination to display products and you have to display page number 2 and number of records to be displayed are 10.

Route definition for query parameters

In your route definition you don't need to add any extra information for query parameters. For example, if you are adding query string after /products in your app URL your route definition will still be ('/products').

router.get('/products', productController.getProducts);

Retrieving query parameters

The values passed for the route parameters are populated in the req.query object, with the name of the query parameter as their respective keys and value of the query parameter as the property value.

For example, if the user makes a get request with http://ROOT_URL/products?limit=10&page=2 then req.query object would look like as given below-

req.query: { limit: '10', page: '2' }

and you can access individual query parameters like this-

const limit = req.query.limit;
const pageNum = req.query.page;

Query parameters Express.js example

This example shows the use of query parameter in Express.js by having a pagination logic for displayed products. In the URL, page number and limit query parameters are added to get the records as per the values passed for query parameters.

Example code is divided into route, controller and model folders with respective files in each of these directories.

routes\products.js

const express = require('express');
const router = express.Router();

const productController = require('../controllers/product');

router.get('/products', productController.getProducts);

module.exports = router;

For routing express.Router() is used to keep routing separate from application logic. There is a get request mapping for '/products' path and the callback function is kept in controllers\product.js file.

controllers\product.js

const Product = require('../models/product');

exports.getProducts = (req, res) => {
    console.log('In controller-', req.query);
    // TODO- do a check for whether value is passed
    const limit = req.query.limit;
    const pageNum = req.query.page;
    const products = Product.getProducts(limit, pageNum);
    res.status(200).send(products);
}

As you can see query parameters are extracted in the getProducts() function and passed as parameters to Product.getProducts() method which is in models directory.

models\product.js

module.exports = class Product {
    static getProducts(limit, pageNum){
        // Some hardcoded products
        const product = [{"id":"1","title":"Laptop", "price":"600"},
            {"id":"2","title":"RAM", "price":"100"}, 
            {"id":"3","title":"Mouse", "price":"50"}, 
            {"id":"4","title":"Keyboard", "price":"120"}];
        // Using array.slice to get the required products
        return product.slice((pageNum - 1) * limit, pageNum * limit);
    }
}

Since the focus is on query parameters so the records are hardcoded here rather than going to the DB. Array.slice() method is used to get the required records that fulfil the pagination criteria.

app.js

const express = require('express');
const app = express();

const port = 3000;
const productRouter = require('./routes/products');
app.use(productRouter);

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

With these files done if you run app.js file and access the URL- http://localhost:3000/products?limit=2&page=2

ExpressJS Query Parameters

That's all for the topic ExpressJS Query Parameters. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment