AZawalar AZawalar - 3 years ago 175
Node.js Question

Using classes in routing express

I decided to rewrite the code from functions to classes. However, I encountered such a problem that my this undefined

Routing

// router.js

const ExampleController = require('./ExampleController');
const instanceOfExampleController = new ExampleController();

// Require express and other dependencies

app.post('/post-to-login', instanceOfExampleController.login) // An error appears inside the method


And controller

// My Controller

class ExampleController {

// Private method
myPrivateMethod(info) {
return info.toUpperCase();
}

login(req, res, next) {
console.log('----------------------');
console.log(this); // Here "this" equal of undefined!
console.log('----------------------');
const someValue = this.myPrivateMethod(req.body.info); // Not work!
res.send(someValue);
};
}

Answer Source

instanceOfExampleController.login.bind(instanceOfExampleController) will do the trick. The function loses its context once it's being called directly.

Alternatively, you can use:

app.post('/post-to-login', function (req, res, next) {
  instanceOfExampleController.login(req, res, next);
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download