1

I have the following controller in nodejs with expressjs, I am trying to call a function in the same controller but I have the following error response this.editarAluno is not a function

Controller

var alunoController = {
  criarAluno: function (req, res) {
    this.editarAluno(req, res);
  },
  editarAluno: function (req, res) {
    console.log('Ok....');
  },
};

module.exports = alunoController;
Kevin B
  • 92,700
  • 15
  • 158
  • 170
Ger
  • 451
  • 1
  • 7
  • 22
  • 1
    Where is the code calling the method that is throwing the error? – Jason Cust Jan 22 '19 at 14:36
  • Whenever you have `this` errors, the problem is most likely present where you call a function, not where you define it. Can you show us where you call `alunoController. criarAluno`? – nem035 Jan 22 '19 at 14:47
  • I'm calling inside the route. router.post('/', security.isLoggedIn, alunoController.criarAluno); – Ger Jan 22 '19 at 16:19

2 Answers2

-1

I'd do it like this :

var alunoController = {
  criarAluno: function (req, res) {
    alunoController.editarAluno(req, res);
  },
  editarAluno: function (req, res) {
    console.log('Ok....');
  },
};

module.exports = alunoController;

Don't count on this but on alunoController because I think that this relates to criarAluno, not alunoController.

dun32
  • 598
  • 4
  • 7
-2

The Aluno Controller is an object ...

You should think to redefine how you construct your controller...

With the following code, the this is scope in the controller class.

class AlunoController {
  criarAluno(req, res) {
    this.editarAluno(req, res);
  }
  editarAluno(req, res) {
    console.log('Ok....');
  }
};

module.exports = new AlunoController();
BENARD Patrick
  • 26,915
  • 13
  • 88
  • 92
  • `this` is the same in both cases. The OPs problem is most likely because they are invoking `criarAluno` and altering `this` – nem035 Jan 22 '19 at 15:04
  • Okay, @candybeer, I'll take the test here now. – Ger Jan 22 '19 at 16:20
  • @EdeGerSil Just per curiosity, was it working for you ? – BENARD Patrick Jan 23 '19 at 10:49
  • The calls to the controller would have to change for this type, so I did not follow this approach, but I did a standalone test on another project and it also works. – Ger Jan 23 '19 at 12:16