Traduzir esta página

Usando o middleware

Express is a routing and middleware web framework with minimal functionality of its own: an Express application is essentially a series of middleware function calls executed during the request-response cycle.

Middleware functions are functions that have access to:

  • The request object (req)
  • The response object (res)
  • The next middleware function in the application’s request-response cycle, commonly named next

As funções do Middleware podem executar as seguintes tarefas:

  • Execute qualquer código.
  • Modify the request and response objects.
  • Encerrar o ciclo de solicitação-resposta.
  • Pass control to the next middleware function.

If a middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Caso contrário, o pedido ficará pendurado.

Um aplicativo Express pode usar os seguintes tipos de middleware:

Você pode carregar o nível de aplicação e middleware de nível de roteador com um caminho de montagem opcional. Multiple middleware functions can also be loaded together, which creates a middleware sub-stack at a mount point.

Midddleware no nível de aplicação

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() functions, where METHOD is the lowercase HTTP method of the request that the middleware function handles, such as get, post, put, or delete.

Middleware without a mount path

The following middleware function runs every time the app receives a request:

index.cjs
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});

Middleware mounted on a path

The following middleware function runs for any type of HTTP request on the /user/:id path:

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

Manipuladores de rota

Este exemplo mostra uma rota e sua função de manipulador (sistema de middleware). A função lida com requisições GET para o caminho /user/:id.

app.get('/user/:id', (req, res) => {
res.send('USER');
});

Middleware sub-stacks

Multiple middleware functions can be loaded together at a mount point to form a middleware sub-stack. This example prints request info for any type of HTTP request to the /user/:id path:

app.use(
'/user/:id',
(req, res, next) => {
console.log('Request URL:', req.originalUrl);
next();
},
(req, res, next) => {
console.log('Request Type:', req.method);
next();
}
);

Multiple route handlers

Os gerenciadores de rotas permitem que você defina várias rotas para um caminho. O exemplo abaixo define duas rotas para solicitações GET para o caminho /user/:id. A segunda via não causará quaisquer problemas, mas nunca será chamada, porque a primeira via termina o ciclo de resposta aos pedidos.

app.get(
'/user/:id',
(req, res, next) => {
console.log('ID:', req.params.id);
next();
},
(req, res) => {
res.send('User Info');
}
);
// handler for the /user/:id path, which prints the user ID
app.get('/user/:id', (req, res) => {
res.send(req.params.id);
});

Skipping to the next route

Call next('route') to skip the remaining middleware functions in a router middleware stack and pass control to the next route.

next('rota') funcionará apenas em funções de middleware que foram carregadas usando as funções app.METHOD() ou router.METHOD().

In the following example, if the user ID is 0, the first handler skips to the next route, which sends a special response:

app.get(
'/user/:id',
(req, res, next) => {
// if the user ID is 0, skip to the next route
if (req.params.id === '0') next('route');
// otherwise pass the control to the next middleware function in this stack
else next();
},
(req, res) => {
// send a regular response
res.send('regular');
}
);
// handler for the /user/:id path, which sends a special response
app.get('/user/:id', (req, res) => {
res.send('special');
});

Reusable middleware arrays

Middleware functions can also be grouped into arrays for better reusability. Este exemplo mostra um array com um sub-stack de middleware que lida com requisições GET para o caminho /user/:id

function logOriginalUrl(req, res, next) {
console.log('Request URL:', req.originalUrl);
next();
}
function logMethod(req, res, next) {
console.log('Request Type:', req.method);
next();
}
const logStuff = [logOriginalUrl, logMethod];
app.get('/user/:id', logStuff, (req, res) => {
res.send('User Info');
});

Midddleware nível de roteamento

Router-level middleware works the same way as application-level middleware, except it is bound to an instance of express.Router().

const router = express.Router();

Carregue o middleware no nível de roteador usando as funções router.use() e router.METHOD().

O código a seguir replica o sistema middleware que é mostrado acima para o middleware no nível de aplicativos, usando o middleware no nível de roteador:

index.cjs
const express = require('express');
const app = express();
const router = express.Router();
// a middleware function with no mount path. This code is executed for every request to the router
router.use((req, res, next) => {
console.log('Time:', Date.now());
next();
});
// a middleware sub-stack shows request info for any type of HTTP request to the /user/:id path
router.use(
'/user/:id',
(req, res, next) => {
console.log('Request URL:', req.originalUrl);
next();
},
(req, res, next) => {
console.log('Request Type:', req.method);
next();
}
);
// a middleware sub-stack that handles GET requests to the /user/:id path
router.get(
'/user/:id',
(req, res, next) => {
// if the user ID is 0, skip to the next route
if (req.params.id === '0') next('route');
// otherwise pass control to the next middleware function in this stack
else next();
},
(req, res) => {
// render a regular page
res.render('regular');
}
);
// handler for the /user/:id path, which renders a special page
router.get('/user/:id', (req, res) => {
console.log(req.params.id);
res.render('special');
});
// mount the router on the app
app.use('/', router);

Skipping out of a router

Use next('router') to skip the rest of the router’s middleware functions and pass control back out of the router instance.

In the following example, the router only responds when the request includes an x-auth header. Otherwise, next('router') exits the router and the app responds with a 401 status:

index.cjs
const express = require('express');
const app = express();
const router = express.Router();
// predicate the router with a check and bail out when needed
router.use((req, res, next) => {
if (!req.headers['x-auth']) return next('router');
next();
});
router.get('/user/:id', (req, res) => {
res.send('hello, user!');
});
// use the router and 401 anything falling through
app.use('/admin', router, (req, res) => {
res.sendStatus(401);
});

Midddleware com erro manipulado

Definir funções intermediárias de manipulação de erros da mesma forma que outras funções de middleware, exceto quatro argumentos em vez de três, especificamente com a assinatura (err, req, res, next):

app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});

O middleware com erros de manipulação sempre toma quatro argumentos. Você deve fornecer quatro argumentos para identificá-lo como uma função de middleware manipulação de erros. Mesmo se você não precisar usar o objeto next , você deve especificá-lo para manter a assinatura. Caso contrário, o objeto próximo será interpretado como um middleware regular e irá falhar em lidar com erros.

Midddleware integrado

O Express tem as seguintes funções de middleware incorporadas:

Midddleware de terceiros

Usar middleware de terceiros para adicionar funcionalidades a aplicativos Express.

Instale o módulo Node.js para a funcionalidade requerida e, em seguida, carregue-o em seu aplicativo ao nível do aplicativo ou no nível do roteador.

O exemplo a seguir ilustra a instalação e o carregamento da função middleware de análise de cookie-parser`.

Terminal window
npm install cookie-parser
index.cjs
const express = require('express');
const app = express();
const cookieParser = require('cookie-parser');
// load the cookie-parsing middleware
app.use(cookieParser());