Node.js and Express - Typeerror: Cannot read Property

Asked

Viewed 2,790 times

2

I’m getting the following console error: Typeerror: Cannot read Property '_id' of Undefined

I’m reading the book "Mean Full Stack Javascript..." from the code house. During the development of the application presented in the book, I obtained the above error. What I am trying to do is save or update a certain data in a list, for now static, on the server. However, after passing through Angularjs(routes and controller) and arriving in Express the controller receives the object sent as Undefined.

Giving a search, some places indicated take a look at the body-parser, but here it is all ok, based on the book and what the guys advised in other pots. However, I could not solve the problem. Follow the codes below:

HTML

<form ng-submit="salvar()" >
<div class="form-group">
    <label for="nome">Nome Completo</label>
    <input class="form-control" type="text" id="nome" name="nome" required ng-model="contato.nome">
</div>
<div class="form-group">
    <label for="email">Email</label>
    <div class="input-group">
        <span class="input-group-addon">@</span>
        <input class="form-control" type="text" id="email" name="email" required ng-model="contato.email">
    </div>
</div>
<div>
    <button type="submit" class="btn btn-primary">Salvar</button>
    <a href="#/" class="btn btn-default">Voltar</a>
</div>

Controller Angularjs

var Contato = $resource('/contatos/:id');

        $scope.salvar = function(){
        $scope.contato.$save()
            .then(function(){
                $scope.mensagem = "Contato salvo com sucesso!";
                $scope.contato = new Contato();
            })
            .catch(function(erro){
                console.log(erro);
            });
    };

Rota Express

var controller = app.controllers.contatoController;

    app.route('/contatos')
        .get(controller.listaDeContatos)
        .post(controller.salvarContato);

    app.route('/contatos/:id')
        .get(controller.obtemContatoPorId)
        .delete(controller.remover)
        .post(controller.salvarContato);

Controller Express

    controller.salvarContato = function(req, res){
    console.log("Chegou até salvarContato!");
    var contato = req.body;
    console.log(contato);
    contato = contato._id ? atualiza(contato) : adiciona(contato);
    res.json(contato);
}

In short. The object arrives in the express Undefined... I’ve reviewed the part of the book that explains about, I’ve looked on the net, until I gave up and came here. rsrs

Any help will be welcome!

Not to be left out, I also leave the body-parser configuration.

ps: the required module name is the same as the dependency in the package.json file

var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:true}));

Vlw!

  • Console expresses error on 5th line of Express Controller above.

  • 1

    Jokshan, if you like console.log(JSON.stringify(contato)); you can put the result here?

  • Hello @Sergio ! The result is Undefined. I believe the object is not recovered when using req.body or it is not even being sent through the post request.

  • JSON.stringify(contato) should not give Undefined... What gives console.log(typeof contacto, contacto || 'vazio');?

  • I identified and fixed the @Sergio issue, thanks for your attention!

  • Okay, if you want to put the solution in the answers. If it is not better to close/delete this question as no one else will know what the problem was nor the solution :)

Show 1 more comment

1 answer

2

I was able to fix it. The problem was in the express configuration file.

I was first calling the express-load to import the files before setting the body-parser. I just reversed the call order and the request worked.

The error in fact was that the object was not coming to the server due to body-parser not being able at the time needed to convert Json to object and vice versa.

I hope I’ve helped someone with my problem!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.