如何在中间件中使用"this"上下文 [英] How to use 'this' context in middleware

查看:94
本文介绍了如何在中间件中使用"this"上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于我的目的,我编写了自己的中间件作为模块,如下所示:

I wrote my own middleware as module for my purposes that looks like the following:

-- myMiddleware.js

module.exports = {
    fn1: function (req, res, next) {
       console.log('fn1');
       next();
    },

    fn2: function (req, res, next) {
        console.log('fn2');
        this.fn1(req, res, function () {
             next();
        });
    }
};

在我的sserver.js中,我将这种中间件用于以下用途:

In my sserver.js I use this middleware as the following:

app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser('your secret here'));

app.use(require('./myMiddleware').fn2);

不幸的是,这不起作用,因为fn2中的此上下文不是myMiddleware.js对象.怎样才能正确使用呢?

Unfortunately that does not work because this context in fn2 in not myMiddleware.js object. How can use proper this?

推荐答案

您不能,"this"属性始终是香草服务器(http.Server)实例或兼容处理程序.

You can't, the 'this' property will always be the vanilla Server (http.Server) instance or compatible handler.

您可以执行以下操作:

var middlewares = {};

module.exports = middlewares;

middlewares.fn1 = function(req, res, next){ ... };

middlewares.fn2 = function(req, res, next){ 
    middlewares.fn1(req, res, next); 
};

这篇关于如何在中间件中使用"this"上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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