Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node.js Route to Controller not applying Controller constructor

I have an express.js application that uses the express.Router() to connect my endpoints to controllers.

My goal is to have an object newed up in the controller constructor so I can use it in all controller functions without having to new it up in each one.

The constructor runs correct, and the object is available within the constructor. But whenever I call any actions of the controller, the object is null.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Here is the router

const express = require('express');
const componentController = require('../controllers/component');

const router = express.Router();

// component routes
router.get('/components', componentController.getComponents);

module.exports = router;

And here is my controller.

const LogService = require('../services/logService');

class ComponentController {
    constructor() {
        this.logger = new LogService('ComponentController');
        this.logger.logDebug('test1','test1');
    }

    async getComponents(req, res) {
        const test = new LogService('ComponentController');
        test.logDebug('test2','test2');

        this.logger.logDebug('test3','test3')
        res.json('');
    }
}

module.exports = new ComponentController();

I want the LogService to be available in the controller actions. The first two logs work correctly, test1 and test2. But test3 throws an error saying logger is undefined.

Why is this.logger undefined in later functions? How can I fix this issue?

>Solution :

try to refactor getComponents to an arrow function.

Here is why: https://javascript.plainenglish.io/this-binding-in-es6-arrow-function-70d80e216238

You can also do this:

router.get('/components', componentController.getComponents.bind(componentController));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading