14
What are middleware and how important it is for the Node platform?
14
What are middleware and how important it is for the Node platform?
20
Middleware is every kind of function that is between an HTTP request and the final response that the server sends back to the client.
For example, using Express.js, a simple GET request would have this code:
var app = express();
app.get('/', function(req, res, next) {
res.send('Hello World!');
});
if you want to log the request type and the url of a request
you can use this simple middleware:
app.use(function(req, res, next) {
console.log(req.method, req.url);
next();
});
The middleware function has 3 parameters, request, response and callback. You can have n middleware processing an HTTP request, chained. When a middleware has just processed it is placed at the end of the code next();
, thus invoking the callback and the code continues to run to the next middleware or final answer.
Middleware is therefore a feature, functions that perform intermediate processes. The most common examples are to interact with the BD, search for static files, handle errors or redirects.
A chaining exepmplo of "middlewares" could be like this:
var express = require('express'), // chamar a app e dar configurações minimas
app = express.createServer(),
port = 1337;
function middleHandler(req, res, next) {
// tratar erros
var err = req.body.foo == null;
if (!err) next();
else res.send("a variavel foo não tem dados!");
}
app.use(function (req, res, next) {
// escrever na BD
console.log(JSON.stringify(req.body));
next();
});
app.use(function (req, res, next) {
// outros processos
next();
});
app.get('/', middleHandler, function (req, res) {
console.log(ultimo passo);
res.send("Obrigado pelo seu registo!");
});
app.listen(port); // iniciar o servidor
console.log('start server');
Note that in this example above the app.get
has a middleware as argument. You can use middleware chained also that way. Here’s a real example:
app.get('/', githubEvents, twitter, getLatestBlog, function(req, res){
res.render('index', {
title: 'MooTools',
site: 'mootools',
lastBlogPost: res.locals.lastBlogPost,
tweetFeed: res.locals.twitter
});
});
This is a example we use on the Mootools website to upload Twitter, Blog and Github posts to upload res
with the variables that the page needs to be processed.
Note: If they use app.use
this middleware will be called in all the request
. If you want to be more specific to for example requests GET you can use as in the examples above app.get('caminho', middleware1, middlware2, etc, function(){ ...
8
When you create a route in your web application you free an area of your application for users to access via browser or other applications via some http client framework. When this route is accessed, two main objects appear in the callback of this function, they are:
**request**: ele é responsável por carregar dados da requisição que esta sendo realizada, geralmente vem com dados do cliente e algums parâmetros de input, como querystrings, parâmetros de rotas e body de um formulário. Em resumo, este objeto contém diversos dados do cliente.
**response**: este objeto permite que o servidor envie uma resposta para o cliente que realizou uma requisição. Aqui você pode enviar um html, json, dados via header, redirecionar a resposta para uma outra requisição, em geral este é um objeto focado em dar uma resposta para o cliente.
Middleware functions that can handle the inputs and outputs of routes before and after a route is processed, that is, you can create a middleware that intercepts and check if a request is sending a specific header and if it is not sending the header it returns an error screen to the user, denying the request to access a particular route of the application, in this case you created and inejtou a middleware that treats a pre-requisition. You can also create a middleware that at the end of each route response, also return a header with response metadata, for example, data paging headers. In this case we are creating a post-requisition middleware. There are no limits when injecting middlewares, you can create and configure N middlewares in your application, however it is always good to understand what are each middlewares and mainly the order that each middleware is injected affects in the processing of a route, that is, if you enter middlewares in a wrong order, as side effect your application may respond or even not correctly process your routes, so it is extremely important to understand what each middleware does and in what order to inject them.
Hello, Vanderson. A middleware to have similar operation to the filters in a JEE application. This my impression is correct?
I don’t know Jee, what I can tell you is that a Middleware is the kind of function that’s between a request and a Sponse. Just like @Sergio said in the example.
Browser other questions tagged node.js function express middleware
You are not signed in. Login or sign up in order to post.
@nbro i answered with focus on express because the question has the tag expressjs. I often use middleware on Node, even if not on express. I can give an example later then.
– Sergio