将依赖项注入Express路由



我需要将我的db对象注入到securityHandler对象中,但我似乎不知道如何做到这一点。

securityHandler.authenticate方法中,我想访问所有的:dbrequestresponse

我试过这个:

app.post('/api/login', securityHandler.authenticate(request, response, db) );

SecurityHandler.prototype.authenticate = function authenticate(request, response, db) {};

编辑:

nane建议将db对象传递给SecurityHandler的构造函数:

var security = new SecurityHandler(db);

SecurityHandler本身看起来是这样的:

function SecurityHandler(db) {
    console.log(db); // Defined
    this.db = db;
}
SecurityHandler.prototype.authenticate = function authenticate(request, response, next) {
    console.log(this.db); // Undefined
};

db对象现在存在于构造函数方法中,但由于某些原因在authenticate方法中是不可访问的。

您可以在express.js中编写一个自定义中间件,并在路由任何请求之前使用它。

有关自定义中间件的更多信息,请参阅-Express.js中间件解密

现在,在这个中间件中,您可以实现与身份验证相关的功能,该功能将在所有请求之前启动,并且您可以在中间件本身中根据您的request.url操作代码。

希望这对你有帮助。谢谢

securityHandler.authenticate(request, response, db)将立即调用authenticate,因为您将把authenticate调用的结果作为回调传递给app.post('/api/login', /*...*/)

你需要这样做:

app.post('/api/login', function(request, response) {
   securityHandler.authenticate(request, response, db);
});

最新更新