ExpressJS Routing
Routing in ExpressJS refers to the process of defining how an application responds to client requests to specific endpoints (URLs). With ExpressJS, you can create routes to handle various HTTP methods (GET, POST, PUT, DELETE, etc.) and serve different content or perform different actions based on the requested URL and HTTP method.
1. Basic Routing
Basic routing in ExpressJS involves defining routes for different URLs and HTTP methods using the app.get()
, app.post()
, app.put()
, app.delete()
, and other
methods provided by the Express application object.
Example:
// Define a route for the homepage
app.get('/', (req, res) => {
res.send('Welcome to the homepage');
});
// Define a route for handling POST requests
app.post('/submit', (req, res) => {
res.send('Form submitted successfully');
});
In this example, a route for the homepage (/
) responds to GET requests with
a welcome message, while a route for handling form submissions (/submit
)
responds to POST requests with a success message.
2. Route Parameters
ExpressJS allows you to define routes with parameters in the URL, which can be accessed in the route handler using
req.params
.
Example:
// Define a route with a parameter
app.get('/users/:id', (req, res) => {
const userId = req.params.id;
res.send(`User ID: ${userId}`);
});
In this example, a route with a parameter (/users/:id
) responds to requests
with the user ID provided in the URL.
3. Route Middleware
ExpressJS allows you to use middleware functions to perform tasks like authentication, logging, and error handling before passing control to route handlers.
Example:
// Middleware function
const authenticate = (req, res, next) => {
// Perform authentication
if (req.isAuthenticated()) {
next();
} else {
res.status(401).send('Unauthorized');
}
};
// Route with middleware
app.get('/profile', authenticate, (req, res) => {
res.send('Profile page');
});
In this example, the authenticate
middleware function checks if the user is
authenticated before allowing access to the profile page.
4. Error Handling
ExpressJS provides built-in error handling middleware to handle errors that occur during request processing.
Example:
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Internal Server Error');
});
This error handling middleware catches errors thrown during request processing and sends an appropriate error response.
5. Conclusion
Routing in ExpressJS is a fundamental aspect of building web applications and APIs. By defining routes, handling route parameters, using middleware, and implementing error handling, developers can create robust and scalable applications with ExpressJS.
Comments
Post a Comment