Home >Web Front-end >JS Tutorial >Understanding and Implementing Middleware in Express.js

Understanding and Implementing Middleware in Express.js

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-09-22 06:21:451107browse

Entendendo e Implementando Middlewares no Express.js

Express.js is one of the most popular frameworks for building web applications with Node.js. It facilitates the creation of RESTful APIs and allows you to structure applications in a modular way. One of the main concepts in Express.js is the use of middlewares. In this article, we will understand what middleware is, how it works and how you can create your own.

What are Middlewares?

Middlewares are functions that have access to the request object (req), the response object (res) and the next() function. They can modify the request and/or response object and control the request-response cycle. A middleware can do several things, such as:

  • Run any code.
  • Modify the request and response.
  • Close the request-response cycle.
  • Call the next middleware in the chain.

The basic signature of a middleware in Express.js is:

function middleware(req, res, next) {
    // Lógica do middleware
    next(); // Chama o próximo middleware
}

Types of Middleware

In Express, we can find several types of middleware:

  1. Application Middleware: These are middlewares that affect the entire application or a set of routes.
  2. Route Middleware: Specific to one or more routes.
  3. Integrated Middleware: Such as express.json() and express.static(), provided directly by Express.
  4. Third Party Middleware: Such as morgan or cors, which you can install to extend the functionality of Express.

How Middleware Works?

When a request is received, it passes through a "middleware chain". Each middleware can process the request and, at the end of its execution, decide whether to call the next middleware (using the next() function) or finalize the response.

const express = require('express');
const app = express();

// Middleware global
app.use((req, res, next) => {
    console.log('Request Type:', req.method);
    next();
});

// Middleware específico para a rota /user
app.use('/user', (req, res, next) => {
    console.log('Middleware para /user');
    next();
});

app.get('/user', (req, res) => {
    res.send('Página do Usuário');
});

app.listen(3000, () => {
    console.log('Servidor rodando na porta 3000');
});

Creating Custom Middleware

In addition to middleware provided by Express or third parties, you can create your own middleware to handle specific functionality, such as authentication, logging, or data manipulation.

Example of a simple authentication middleware:

function autenticar(req, res, next) {
    const token = req.header('Authorization');
    if (!token) {
        return res.status(401).send('Acesso negado. Token não fornecido.');
    }
    try {
        // Lógica para validar o token
        next(); // Continua para o próximo middleware
    } catch (err) {
        res.status(400).send('Token inválido.');
    }
}

app.use(autenticar); // Aplica o middleware para todas as rotas

Third-Party Middleware

Express also allows the use of third-party middleware, which can be installed via npm. Some of the most popular are:

  • morgan: For HTTP logs.
  • helmet: For security, setting protective HTTP headers.
  • cors: To enable CORS (Cross-Origin Resource Sharing).

Installing and using Morgan:

npm install morgan
const morgan = require('morgan');

// Middleware de log
app.use(morgan('tiny'));

app.get('/', (req, res) => {
    res.send('Hello World');
});

Order of Middleware

The order in which you define the middlewares is important, as they are executed in the sequence in which they are registered. For example, if you define authentication middleware after a route that requires authentication, it will not run for that route.

app.use(express.json()); // Middleware para parsear JSON

app.post('/secure-data', autenticar, (req, res) => {
    res.send('Acesso a dados seguros');
});

Finalizing Middleware

If a middleware does not call the next() function, it will interrupt the request-response cycle. This can be useful in cases where you want to finalize the request within the middleware itself, such as in an authentication check:

function autenticar(req, res, next) {
    if (!req.header('Authorization')) {
        return res.status(403).send('Não autorizado');
    }
    next();
}

Conclusion

Middlewares are an essential part of building applications with Express.js, allowing great flexibility and modularity. By mastering the use of middleware, you will be able to structure your APIs efficiently, reusing code and adding features such as authentication, security and data manipulation in a simple and scalable way.

If you're not already using custom middleware in your projects, start with something simple, like a logging or authentication middleware, and experience the modularity and flexibility that Express.js offers!


Did you like the article? Don't forget to share with your fellow developers!

The above is the detailed content of Understanding and Implementing Middleware in Express.js. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn