路由后的Node Express 4中间件 [英] Node Express 4 middleware after routes

查看:106
本文介绍了路由后的Node Express 4中间件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在升级到Express 4和删除app.router之后,我努力使中间件在路由执行后得以执行.

Following the upgrade to Express 4, and the removal of app.router, I'm struggling to get middleware to execute after routes execute.

例如以下代码以"hello"正确响应,但从不调用已配置的中间件

e.g. the following code correctly responds with "hello", but never calls the configured middleware

var express = require( "express" )();

express.get( "/", function( req, res ) {

    res.send( "hello" );

} );
express.use( function( req, res, next ) {

    console.log( "world" );
    next();

} );

express.listen( 8888 );

澄清:

以下代码在控制台上显示"before",但不显示"after":

the following code shows "before" on the console, but not "after":

var express = require( "express" )();

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

    console.log( "before" );
    next();

} );
express.get( "/", function( req, res ) {

    res.send( "hello" );

} );
express.use( function( req, res, next ) {

    console.log( "after" );
    next();

} );

express.listen( 8888 );

推荐答案

对于Express 4,第二个示例中的"after"函数永远不会调用,因为中间函数永远不会调用next().

In regards to Express 4, the "after" function from your second example never gets called because the middle function never calls next().

如果要调用"after"函数,则需要像这样从中间函数添加并调用下一个回调:

If you want the "after" function to get called, then you need to add and call the next callback from your middle function like this:

var express = require( "express" )();

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

  console.log( "before" );
  next();

} );
express.get( "/", function( req, res, next ) {

  res.send( "hello" );
  next();      // <=== call next for following middleware 

} );
express.use( function( req, res, next ) {

  console.log( "after" );
  next();

} );

express.listen( 8888 );

res.send() 将标头和响应写回到客户端.

res.send() writes the headers and response back to the client.

当心,一旦调用了res.send(),您就不想更新响应头或内容.但是您可以执行其他任务,例如数据库更新或日志记录.

Beware, that once res.send() has been called, you won't want to update your response headers or contents. But you can do other tasks like database updates or logging.

请注意,express会查看中间件函数中参数的数量,并且会执行不同的逻辑.以表达错误处理程序为例,该方法定义了4个参数.

Note that express looks at the the number of arguments in the middleware function and does different logic. Take express error handlers for example, which have 4 parameters defined.

表达错误处理程序签名:app.use(function(err, req, res, next) {});

express error handler signature: app.use(function(err, req, res, next) {});

在中间件链中的最后一个项目上调用下一个是可选的,但如果您更改周围的内容,则可能是个好主意.

Calling next on the very last item in your middleware chain is optional, but probably a good idea in case you ever change things around.

这篇关于路由后的Node Express 4中间件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆