Why we should use Express.js
1. Routing Made Simple
Express simplifies routing by allowing you to define routes for different HTTP methods (GET, POST, PUT, DELETE) and URL paths. With Express, you can easily handle different types of requests with clean and readable code.
Handling a get request
app.get("/about", (req, res) => { res.send("About Us");});2. Middleware Support
Express allows you to use middleware functions to process requests before they reach your route handlers. Middleware functions can handle tasks such as logging, authentication, error handling, and more. This allows for cleaner, reusable code.
A simple logging middleware
app.use((req, res, next) => { console.log(`Request URL: ${req.url}`); next(); // Pass the request to the next middleware});In this example, the logging middleware is used to log the URL of every incoming request. The next() function is called to pass the request on to the next middleware or route handler, ensuring the request processing continues.
3. Template Engine Support
Express can integrate easily with various template engines, such as EJS, Pug, and Handlebars. This allows you to generate dynamic HTML pages based on data from the server, enabling you to separate the logic of your application from the presentation layer.
Using EJS as a template engine
app.set("view engine", "ejs");
app.get("/", (req, res) => { res.render("index", { title: "Express" });});Here, we set up EJS as the view engine using app.set('view engine', 'ejs'). Then, when a GET request is made to the root path (/), we use res.render() to render the index view and pass dynamic data ({ title: 'Express' }) to the template, which will be injected into the HTML.
5. Error Handling
Express provides built-in mechanisms to handle errors in your application. You can set up custom error-handling middleware to catch and manage any errors that occur during request processing.
Custom error-handling middleware
app.use((err, req, res, next) => { console.error(err.stack); // Log the error stack trace res.status(500).send("Something broke!"); // Respond with a 500 status and a message});In this example, we define a custom middleware that catches errors by specifying four parameters: err, req, res, and next. Whenever an error occurs in the application, this middleware logs the error stack and sends a response with a 500 status code, indicating an internal server error. You can further customize the error message or handle specific types of errors more gracefully.