简体   繁体   中英

Dependency inject into Express route

I need to inject my db object into the securityHandler object, but I can't seem to work out how to do it.

In the securityHandler.authenticate method I want to have access to all: db , request and response .

I've tried this:

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

and

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

EDIT:

nane suggested passing the db object to the constructor of SecurityHandler:

var security = new SecurityHandler(db);

SecurityHandler itself looks like this:

function SecurityHandler(db) {
    console.log(db); // Defined
    this.db = db;
}

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

The db object now exists in the constructor method, but for some reason is unaccessible in the authenticate method.

securityHandler.authenticate(request, response, db) would immediately call authenticate as of that you would pass the result of the authenticate call as callback to app.post('/api/login', /*...*/) .

You would need to do it that way:

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

You can write a custom middleware in express.js and use it before route any request.

For more about custom middleware - you can refer - Express.js Middleware Demystified

Now in this middleware you can implement authentication related functionality which will fire before all request and you can manipulate code on basis of your request.url in the middleware itself.

Hope this will help you. Thanks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM