0

I have a class with two methods:

var express = require('express');

class TestClass{
    constructor() {}

    first() {
        var app = express();
        var path = require('path');
        app.use( express.urlencoded({ extended: true }) )
        app.use( express.json() );
    
        app.post('/centroid', function(req, res) {
            this.second(req.body);
        });

        app.listen(4444);
    }
    second(data) { console.log(data) }
}


module.exports = TestClass;

When I try to reference the second method while using this, I get an error that this is undefined.

I have looked into .bind() method, but it seems that I can't use that with passing the req.body argument. Because it would require to bind it in the callback of the .post function.

How can i resolve this and use second() method in a callback of a post function?

Sanlyn
  • 139
  • 1
  • 12
  • 1
    Make the callback to `app.post(` and **arrow** function, so it keeps the same `this`. – trincot Jun 02 '22 at 14:01
  • As @trincot suggested, try to use arrow function app.post('/centroid', (req, res) => ...). There is also option to bind "this" with some variable, for example var _self = this;. – lemek Jun 02 '22 at 14:12

0 Answers0