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.
Importing Required Modules:
const express = require('express');
const router = require('../router/router.config');
express: The core Express module is required to create an Express application.router: This is the router configuration that contains all the route definitions, imported from ../router/router.config.Creating the Express App:
const app = express()
Body Parsers:
app.use(express.json());
app.use(express.urlencoded({
extended: true
}));
app.use(express.json()): Middleware to parse incoming requests with JSON payloads.app.use(express.urlencoded({ extended: true })): Middleware to parse incoming requests with URL-encoded payloads. The extended: true option allows for rich objects and arrays to be encoded into the URL-encoded format.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.
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.
null.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.
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;
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.
Understanding Normal Middleware and Error Handling Middleware in Express.Js