在路由Express中使用类



我决定将代码从函数重写为类。但是,我遇到了一个问题,以至于我的这个未定义

路由

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

和控制器

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

instanceOfExampleController.login.bind(instanceOfExampleController)将做到这一点。该功能一旦被直接称为上下文就会失去其上下文。

另外,您可以使用:

app.post('/post-to-login', function (req, res, next) {
  instanceOfExampleController.login(req, res, next);
});

最新更新