Adding Parameters to Routes in Express JS
You can capture dynamic values from URLs using parameters:
- :id is a placeholder for a dynamic value.
- req.params: An object containing the captured parameter values.
Navigate to http://localhost:3000/users/<id> (or the port you specified). You should see “User with ID: <Id you mentioned in the URL >” is displayed.
const express = require('express');
const app = express();
const port = process.env.PORT || 3000; // Use environment variable or default to port 3000
app.get('/users/:id', (req, res) => {
const userId = req.params.id; // Access the parameter value
res.send(`User with ID: ${userId}`);
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Getting Started with Express JS
Express JS is a versatile, minimalist web framework for NodeJS that simplifies the development of back-end applications and APIs for web and mobile applications. Its flexibility and powerful features enable you to create robust and scalable web projects with minimal code, making it a popular choice among developers. Express is released as free and open-source software under the MIT License.
Table of Content
- Installing Express JS
- Running a simple web server in Express JS
- Adding Routes for Handling request in Express JS
- Adding Parameters to Routes in Express JS
- Modularizing Routes with Express Router:
- Adding Middleware for Processing Requests in Express JS
- Adding Error Handling Middleware in Express JS