Routing is a fundamental aspect of Express.js, enabling the application to respond to client requests at specific endpoints (URIs) and defining how the application handles these requests. This chapter will cover routes and route handlers in Express.js from basic to advanced concepts, providing comprehensive explanations and examples.
Routes in Express.js are essentially the URL patterns that define how the application responds to client requests. A route is defined by a path and one or more HTTP methods.
Basic routing involves defining endpoints and specifying how the application should respond to client requests.
const express = require('express');
const app = express();
app.get('/', (req, res) => {
res.send('Home Page');
});
app.get('/about', (req, res) => {
res.send('About Page');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
app.get('/', (req, res) => {...})
: Defines a GET route for the root URL (/
).app.get('/about', (req, res) => {...})
: Defines a GET route for the /about
URL.res.send(...)
: Sends a response to the client.http://localhost:3000
displays “Home Page”.http://localhost:3000/about
displays “About Page”.Route parameters are used to capture values specified at certain positions in the URL.
app.get('/users/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
:id
: A route parameter that captures the value in the URL.req.params.id
: Accesses the captured value.Output: Navigating to http://localhost:3000/users/123
displays “User ID: 123”.
Query strings are used to pass additional information in the URL in the form of key-value pairs.
app.get('/search', (req, res) => {
res.send(`Search Query: ${req.query.q}`);
});
req.query.q
: Accesses the query string parameter q
.Output: Navigating to http://localhost:3000/search?q=express
displays “Search Query: express”.
Express.js supports various HTTP methods, allowing you to define routes for GET, POST, PUT, DELETE, and more.
app.post('/submit', (req, res) => {
res.send('Form Submitted');
});
app.put('/update/:id', (req, res) => {
res.send(`Updated User ID: ${req.params.id}`);
});
app.delete('/delete/:id', (req, res) => {
res.send(`Deleted User ID: ${req.params.id}`);
});
Explanation:
app.post(...)
: Defines a POST route.app.put(...)
: Defines a PUT route.app.delete(...)
: Defines a DELETE route.Output:
/submit
displays “Form Submitted”./update/123
displays “Updated User ID: 123”./delete/123
displays “Deleted User ID: 123”.Route handlers are functions that handle the HTTP requests. You can define multiple route handlers for a single route.
const logRequest = (req, res, next) => {
console.log(`${req.method} request for ${req.url}`);
next();
};
const sendResponse = (req, res) => {
res.send('Request logged and response sent');
};
app.get('/log', logRequest, sendResponse);
Explanation:
logRequest
: A middleware function that logs the request.sendResponse
: A function that sends the response.app.get('/log', logRequest, sendResponse)
: Uses both functions as route handlers.Output: Navigating to http://localhost:3000/log
logs the request and displays “Request logged and response sent”.
Middleware functions can be used in routes to perform tasks such as authentication, validation, and logging.
const authenticate = (req, res, next) => {
if (req.query.auth === 'true') {
next();
} else {
res.send('Authentication required');
}
};
app.get('/protected', authenticate, (req, res) => {
res.send('Protected Resource');
});
Explanation:
authenticate
: A middleware function that checks for an authentication query parameter.app.get('/protected', authenticate, (req, res) => {...})
: Uses the authenticate
middleware.Output:
http://localhost:3000/protected?auth=true
displays “Protected Resource”.http://localhost:3000/protected
displays “Authentication required”.The Express Router allows you to create modular, mountable route handlers.
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('User List');
});
router.get('/:id', (req, res) => {
res.send(`User ID: ${req.params.id}`);
});
module.exports = router;
const express = require('express');
const app = express();
const userRoutes = require('./userRoutes');
app.use('/users', userRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
userRoutes.js
: Defines a router with routes for /users
and /users/:id
.app.use('/users', userRoutes)
: Mounts the userRoutes
router on the /users
path.http://localhost:3000/users
displays “User List”.http://localhost:3000/users/123
displays “User ID: 123”.Nested and modular routing help organize routes in a scalable way, especially for large applications.
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
res.send('Admin Dashboard');
});
router.get('/users', (req, res) => {
res.send('Admin User Management');
});
module.exports = router;
const express = require('express');
const app = express();
const adminRoutes = require('./adminRoutes');
app.use('/admin', adminRoutes);
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
adminRoutes.js
: Defines routes under the /admin
path.app.use('/admin', adminRoutes)
: Mounts the adminRoutes
router on the /admin
path.http://localhost:3000/admin
displays “Admin Dashboard”.http://localhost:3000/admin/users
displays “Admin User Management”.Error handling middleware can be used to catch and handle errors in your application.
app.get('/error', (req, res, next) => {
const err = new Error('Something went wrong!');
next(err);
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Internal Server Error');
});
app.get('/error', (req, res, next) => {...})
: Simulates an error and passes it to the next middleware.app.use((err, req, res, next) => {...})
: Error handling middleware that logs the error and sends a response.Output: Navigating to http://localhost:3000/error
logs the error and displays “Internal Server Error”.
Understanding routes and route handlers is crucial for building efficient and maintainable Express.js applications. This chapter covered basic routing, route parameters, query strings, handling different HTTP methods, using middleware, modular routing with the Express Router, and error handling.Happy coding !❤️