tutorial node javascript node.js express web middleware

javascript - node - Entender el middleware y el controlador de ruta en Express.js



npm express (3)

Deberías mirar la documentación de Express. Está lleno de recursos que encontrarás útiles, especialmente si eres nuevo en Express. Aquí hay algunos enlaces a las secciones relevantes de la documentación con respecto a su pregunta.

Espero que esto ayude.

Estoy tratando de entender cómo funcionan el middleware y los manejadores de ruta en Express. En Desarrollo web con Node y Express , el autor ofrece un ejemplo de una ruta y un middleware interesantes en acción, pero no proporciona los detalles reales.

¿Puede alguien ayudarme a entender lo que sucede en cada paso en el siguiente ejemplo para que pueda estar seguro de que estoy pensando correctamente al respecto? Aquí está el ejemplo (con mi comprensión y preguntas en los comentarios):

//get the express module as app var app = require(''express'')(); //1. when this module is called, this is printed to the console, always. app.use(function(req, res, next){ console.log(''/n/nALLWAYS''); next(); }); //2. when a route /a is called, a response ''a'' is sent and the app stops. There is no action from here on app.get(''/a'', function(req, res){ console.log(''/a: route terminated''); res.send(''a''); }); //3. this never gets called as a consequence from above app.get(''/a'', function(req, res){ console.log(''/a: never called''); }); //4. this will be executed when GET on route /b is called //it prints the message to the console and moves on to the next function //question: does this execute even though route /a (2) terminates abruptly? app.get(''/b'', function(req, res, next){ console.log(''/b: route not terminated''); next(); }); //5. question: this gets called after above (4)? app.use(function(req, res, next){ console.log(''SOMETIMES''); next(); }); //6. question: when does this get executed? There is already a function to handle when GET on /b is called (4) app.get(''/b'', function(req, res, next){ console.log(''/b (part 2): error thrown'' ); throw new Error(''b failed''); }); //7. question: I am not sure when this gets called... ? app.use(''/b'', function(err, req, res, next){ console.log(''/b error detected and passed on''); next(err); }); //8. this is executed when a GET request is made on route /c. It logs to the console; throws an error. app.get(''/c'', function(err, req){ console.log(''/c: error thrown''); throw new Error(''c failed''); }); //9. question: this catches the above error and just moves along? app.use(''/c'', function(err, req, res, next) { console.log(''/c: error deteccted but not passed on''); next(); }); //10. question: this follows the above and prints an error based on above? //This also sends a 500 reponse? app.use(function(err, req, res, next){ console.log(''unhandled error detected: '' + err.message); res.send(''500 - server error''); }); //11. question: this is the catch all for something that falls through and sends a 404? app.use(function(req, res){ console.log(''route not handled''); res.send(''404 - not found''); }); //12. This app listens on the 3000 port. app.listen(3000, function(){ console.log(''listening on 3000''); });


En Express, el middleware de secuencia que se registra marca una gran diferencia, cuando Express recibe una solicitud, simplemente ejecuta el middleware registrado y que coincide con la URL solicitada.

Express Middleware tiene la siguiente firma

function(req,res,next){}

req: request object. res: response object. next: next middleware thunk.

Especial middleware de manejo de errores

function(err, req,res,next){}

err: error that was caught req: request object. res: response object. next: next middleware thunk.

Estoy actualizando los comentarios en el código mismo

//get the express module as app var app = require(''express'')(); //1. when this *middleware* is called, this is printed to the console, always. //As this is first registered middleware, it gets executed no matter what because no url match were provided. This middleware does not stop the middleware chain execution as it calls next() and executes next middleware in chain. app.use(function(req, res, next){ console.log(''/n/nALLWAYS''); next(); }); //2. when a route /a is called, a response ''a'' is sent and //the app stops. There is no action from here on //chain stops because this middleware does not call next() app.get(''/a'', function(req, res, next){ console.log(''/a: route terminated''); res.send(''a''); }); //3. this never gets called as a consequence from above //because (2) never calls next. app.get(''/a'', function(req, res){ console.log(''/a: never called''); }); //4. this will be executed when GET on route /b is called //it prints the message to the console and moves on to the next function //question: does this execute even though route /a (2) terminates abruptly? //app.get(''/b'' ... does not depend in any way on (2). as url match criteria are different in both middleware, even if /a throws an exception, /b will stay intact. but this middleware will get executed only at /b not /a. i.e. if /a calls next(), this middleware will not get executed. app.get(''/b'', function(req, res, next){ console.log(''/b: route not terminated''); next(); }); //5. question: this gets called after above (4)? //Yes, as (4) calls next(), this middleware gets executed as this middleware does not have a url filter pattern. app.use(function(req, res, next){ console.log(''SOMETIMES''); next(); }); //6. question: when does this get executed? There is already a function to handle when GET on /b is called (4) //As (4) calls next(), (5) gets called, again (5) calls next() hence this is called. if this was something other ''/b'' like ''/bbx'' this wouldn''t get called --- hope this makes sense, url part should match. app.get(''/b'', function(req, res, next){ console.log(''/b (part 2): error thrown'' ); throw new Error(''b failed''); }); //7. question: I am not sure when this gets called... ? // This happens (4) calls next() -> (5) calls next() -> (6) throws exception, hence this special error handling middleware that catches error from (6) and gets executed. If (6) does not throw exception, this middleware won''t get called. //Notice next(err) this will call (10). -- as we are passing an error app.use(''/b'', function(err, req, res, next){ console.log(''/b error detected and passed on''); next(err); }); //8. this is executed when a GET request is made on route /c. It logs to the console; throws an error. app.get(''/c'', function(err, req){ console.log(''/c: error thrown''); throw new Error(''c failed''); }); //9. question: this catches the above error and just moves along? //Yes, as this middleware calls next(), it will move to next matching middleware. so it will call (11) and not (10) because (10) is error handling middleware and needs to be called like next(err) app.use(''/c'', function(err, req, res, next) { console.log(''/c: error deteccted but not passed on''); next(); }); //10. question: this follows the above and prints an error based on above? //Which ever middleware from above calls next(err) will end up calling this one. ie. (7) does so. //This also sends a 500 response? //This just sends text as ''500 - server error'' //in order to set status code you''ll need to do res.status(500).send ... app.use(function(err, req, res, next){ console.log(''unhandled error detected: '' + err.message); res.send(''500 - server error''); //Also set status code //res.status(500).send(''500 - server error''); }); //11. question: this is the catch all for something that falls through and sends a 404? //No, this does not catch error, as in (7). This route will get elected when non of the above middleware were able to respond and terminate the chain. So this is not an error handling route, this route just sends 404 message if non of the above routes returned a response and stopped chain of execution app.use(function(req, res){ console.log(''route not handled''); res.send(''404 - not found''); //Also set status code //res.status(400).send(''404 - not found''); }); //12. This app listens on the 3000 port. app.listen(3000, function(){ console.log(''listening on 3000''); });

Espero que esto te ayude a entender el flujo.

Avíseme si necesita más aclaraciones.


El middleware puede ser genial de usar, y un poco difícil de entender, al principio. Lo más importante para recordar en middleware es

  • Secuencia
  • función next ()
  • Secuencia
    Como se mencionó en las respuestas anteriores, la secuenciación es muy importante en el middleware. Dado que el middleware se ejecuta uno tras otro, intente comprender el código estrictamente de arriba a abajo

    app.use(function(req,res,next){

    Como el código anterior no especifica ninguna ruta, como, / a o / b, este tipo de middleware se ejecutará cada vez que se golpee su API. Por lo tanto, este middleware siempre se ejecutará.

    app.use(function(err,req,res,next){

    Comprenda que cuando app.use tiene 4 argumentos, Express lo identifica como un middleware que maneja errores. Entonces cualquier error lanzado o creado en la ejecución pasará a través de este middleware.
    Por lo tanto, el # 11 NO es un error que maneja el middleware. Simplemente detiene la cadena de middleware, ya que no tiene la función next () Y es el último middleware en la secuencia.
    También debe comprender ahora que # 7 es un middleware que maneja errores, y obtiene su error desde el # 6, para la ruta / b. # 7 maneja el error pasado en err, y luego pasa el parámetro de error a la función next ().

    siguiente()
    next () es simplemente la función que pasa el control a lo largo de la cadena. Si considera que un middleware no es suficiente para esa ruta en particular (o incluso para ninguna ruta), puede invocar la función next (), que pasará el control al siguiente middleware válido.
    Puede especificar la validez usando las rutas, o hacer que sea de naturaleza universal, por ejemplo, # 9 y # 10. El error del n. ° 9 no pasará al n. ° 10. Esto se debe a que su próximo () en el n. ° 9 no pasó un argumento err, y por lo tanto el n. ° 10, que es un middleware que maneja un error, no lo detectará. # 9 llegará al # 11