In Express.js, routing is a mechanism that defines how an application responds to client requests at specific endpoints or URLs.
Routing in Express helps organize the code and manage different parts of an application based on the requested resource.
Here's an overview of routing in Express.js:
// Handling a GET request at the root URL "/" app.get('/', (req, res) => { res.send('Hello, World!'); }); // Handling a POST request at the "/submit" URL app.post('/submit', (req, res) => { res.send('Form submitted!'); }); // Handling a PUT request at the "/update" URL app.put('/update', (req, res) => { res.send('Resource updated!'); }); // Handling a DELETE request at the "/delete" URL app.delete('/delete', (req, res) => { res.send('Resource deleted!'); });
We can define routes using various HTTP methods such as "GET", "POST", "PUT", "DELETE", etc.
const express = require('express'); const app = express(); const PORT = process.env.PORT || 3000; // Handling a GET request at the root URL "/" app.get('/', (req, res) => { res.send('Hello, World!'); }); // Handling a POST request at the "/submit" URL app.post('/submit', (req, res) => { res.send('Form submitted!'); }); // Handling a PUT request at the "/update" URL app.put('/update', (req, res) => { res.send('Resource updated!'); }); // Handling a DELETE request at the "/delete" URL app.delete('/delete', (req, res) => { res.send('Resource deleted!'); }); app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
app.get('/user/:id', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); });
Parameters can be added to routes to capture values from the URL.
accessing /user/778899 would set req.params.id to 778899.
app.get('/user/:id?', (req, res) => { const userId = req.params.id; res.send(`User ID: ${userId}`); });
Parameters can be made optional by using a question mark ?.
Here, /user and /user/123 would both work.
const middleware = (req, res, next) => { // Middleware logic next(); }; app.get('/protected', middleware, (req, res) => { res.send('Access Granted!'); });
We can have multiple handlers for a single route.
app.get(/^\/users\/(\d+)$/, (req, res) => { const userId = req.params[0]; res.send(`User ID: ${userId}`); });
"middleware" is a function executed before the main route handler.
const express = require('express'); const router = express.Router(); const app = express(); // Middleware to parse JSON and URL-encoded data app.use(express.json({ limit: "50mb" })); app.use(express.urlencoded({ extended: true, parameterLimit: 50000 })); const PORT = process.env.PORT || 3000; router.get('/page', (req, res) => { res.send('This is a page.'); }); app.use('/admin', router); // Listening on the 3000 port app.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Routes can match patterns using regular expressions.
Here, the route matches URLs like /users/778899.
Express routers allow us to modularize our routes.
Requests to http://localhost:3000/admin/page will be handled by the above router endpoint.