In this section, we will cover how to configure an Express application, including setting up middleware for parsing request bodies, handling routes, and managing errors. This configuration is crucial for building a robust and efficient web application.

Steps

  1. Importing Required Modules:

    const express = require('express');
    const router = require('../router/router.config');
    
  2. Creating the Express App:

    const app = express()
    
  3. Body Parsers:

    app.use(express.json());
    app.use(express.urlencoded({
        extended: true
    }));
    
  4. 404 Error Handling:

    app.use((req, res, next) => {
        next({ status: 404, message: "Resource not Found" });
    });
    

    This middleware catches all requests that don't match any route and forwards a 404 error to the error handling middleware.

  5. Error Handling Middleware:

    app.use((err, req, res, next) => {
        let status = err.status || 500;
        let message = err.message || "Server error...";
        let result = err.detail || null;
    
        res.status(status).json({
            result: result,
            meta: null,
            message: message
        });
    });
    

    This middleware handles all errors passed to it. It extracts the status, message, and any additional details from the error object and sends a JSON response with the appropriate status code.

  6. Exporting the App:

    module.exports = app;
    

    Exports the configured Express application so it can be used in other parts of the project, such as the server setup.


Code Overview

Here is the code snippet for the Express configuration:

const express = require('express');
const router = require('../router/router.config');

const app = express();

// Body parsers
app.use(express.json());
app.use(express.urlencoded({
    extended: true
}));

// Endpoint
app.use(router);

// 404 error
app.use((req, res, next) => {
    next({ status: 404, message: "Resource not Found" });
});

// Error handling middleware
app.use((err, req, res, next) => {
    let status = err.status || 500;
    let message = err.message || "Server error...";
    let result = err.detail || null;

    res.status(status).json({
        result: result,
        meta: null,
        message: message
    });
});

module.exports = app;

Conclusion

This Express configuration sets up essential middleware for request parsing, routing, and error handling. It ensures that your application can correctly interpret incoming requests, manage routes, and gracefully handle errors, providing meaningful responses to the client. This configuration forms the backbone of a well-structured Express application, ready to handle various web application needs.

Reference

Express - node web framework

Understanding Normal Middleware and Error Handling Middleware in Express.Js