AZawalar AZawalar - 3 years ago 184
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


// router.js

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

// Require express and other dependencies'/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(this); // Here "this" equal of undefined!
const someValue = this.myPrivateMethod(; // Not work!

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:'/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