Working with Routes in Express.js
Overview
Routing in Express.js allows you to define the endpoints of your web application. Each route can respond to different HTTP methods (GET, POST, PUT, DELETE) and can be configured to handle various URL paths.
Basic Routing
You can define routes using the app.get()
, app.post()
, and other similar methods:
const express = require('express');
const app = express();
const PORT = 3000;
// Basic GET route
app.get('/', (req, res) => {
res.send('Welcome to the Home Page!');
});
// Basic POST route
app.post('/submit', (req, res) => {
res.send('Form submitted!');
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
In this example, we define a GET route for the home page and a POST route for form submissions.
Route Parameters
Express allows you to define dynamic routes using route parameters:
app.get('/user/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID is ${userId}`);
});
Here, :id
is a route parameter that can be accessed via req.params.id
.
Query Parameters
Query parameters can also be handled in Express routes:
app.get('/search', (req, res) => {
const query = req.query.q;
res.send(`Search query: ${query}`);
});
In this example, the query parameter q
can be accessed using req.query.q
.
Middleware in Routes
You can use middleware functions to execute code before your route handlers:
const checkAuth = (req, res, next) => {
// Authentication logic here
console.log('User authenticated');
next(); // Proceed to the next middleware or route handler
};
app.get('/protected', checkAuth, (req, res) => {
res.send('This is a protected route.');
});
The checkAuth
middleware runs before the route handler for the protected route.