Home >Web Front-end >JS Tutorial >Understanding and Implementing Middleware in 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.
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:
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 }
In Express, we can find several types of middleware:
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'); });
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
Express also allows the use of third-party middleware, which can be installed via npm. Some of the most popular are:
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'); });
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'); });
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(); }
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!