Back to Express JS Course

Express JS Course

In Express JS, route parameters are used to capture values specified at certain positions in the URL. They are defined by placing a colon (:) before the parameter name in the route path.

Lets see an example where we fetch the user based on id.

import express from "express" const app = express(); const PORT = process.env.PORT || 5000; const mockUsers = [ { id: 1, name: 'Praveen', designation: 'Technical Architect', city: 'Hyderabad' }, { id: 2, name: 'Prasad', designation: 'Technical Lead', city: 'Bangalore' }, { id: 3, name: 'Anusha', designation: 'Lead Developer', city: 'Chennai' }, ]; // Route to get a single user by ID app.get('/api/v1_0/users/:id', (req, res) => { const parsedId = parseInt(req.params.id); if (isNaN(parsedId)) res.status(400).send({ msg: "Bad Request. Invalid ID" }); const findUser = mockUsers.find((user) => user.id === parsedId); if (!findUser) res.status(404).send({ msg: "ID Not Found" }); res.send(findUser); }); app.listen(PORT, () => console.log(`Running on Port ${PORT}`));

There are 3 scenarios here,

  • Bad Request

screenshot of the app

  • ID Not Found

screenshot of the app

  • Success

screenshot of the app