How to use the 'this' context in middleware

I wrote my own middleware as a module for my purposes, which looks like this:

-- 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(); }); } }; 

In my sserver.js, I use this middleware as follows:

 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); 

Unfortunately, this does not work, because this context in fn2 is not in the myMiddleware.js object. How can I use this correctly?

+4
source share
2 answers

You cannot, the 'this' property will always be an instance of vanilla Server (http.Server) or a compatible handler.

You can do it:

 var middlewares = {}; module.exports = middlewares; middlewares.fn1 = function(req, res, next){ ... }; middlewares.fn2 = function(req, res, next){ middlewares.fn1(req, res, next); }; 
+1
source

This is not because of middlewares.
Whenever a function is passed as arguments to javascript, it loses context. Express skips middlewares around as arguments. So that’s why.

There are several ways to bind context. You can use the function apply, call, closure or easier

+8
source

Source: https://habr.com/ru/post/1499556/


All Articles