I'm developing a simple API in node with pure javascript classes. I'm declaring all my routes in a single file then another one just for the controllers logic.
routes.js
const express = require('express');
const router = express.Router();
const MyController = require('../controllers/my.controller');
const myController = new MyController();
router.post('/', myController.test);
module.exports = router;
MyController.js
class MyController {
constructor() {
this.valueA = 10;
this.valueB = 30;
}
test() {
// some logic
// but values from constructor always undefined
return this.valueA;
}
...
}
module.exports = MyController;
but when I tried to call this route on my localhost, I always get:
TypeError: Cannot read property 'valueA' of undefined
If this class is always initialized when call the routes file, couldn't I get the values from the constructor?
router.post('/', myController.test.bind(myController));posthandling function is, at the least, missingreqandresarguments. It still needs to obey the express middleware signature.resor you do your work and callnext(). If that's not your intention, you have no reason to use express.js at all. That's the whole reason you use express. Middleware chaining.