Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

519
Visualizações
req.body for ID is always undefined but my client side is getting the right value by jQuery .click() call

I swear it was working few days ago, so this behavior is really strange for me. Let me show you my code on client side

$(document).ready(function() {
    $("button").click(function() {
       alert(event.currentTarget.id+"------"+event.currentTarget.value);
       $.post( "/vote", {id:event.currentTarget.id,count:event.currentTarget.value}, $(this).serialize(),
           function(res) {
           }
       );
    })                  
})                      

As you can see, I tried to passed both id and value back to server once the button clicked. So far everything here is good because I can see the alert pop-up on screen with the correct id number and value (Output example -> aaa------23). Now take a look on my server side code.

app.post('/vote', function(req, res) {
    var id = req.body.id;
    var count = req.body.count;

    console.log("id: " + id);
    console.log("count: " + count);

    res.sendStatus(200);
    res.end();
});

When execute to the line var id = req.body.id, the system returns

TypeError: Cannot read property id of undefined.

count will have the same result.

Is there anything obvious I am missing here? Because I swear it was working before and I haven't touch this part of the code since then. Thanks for the help.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Make sure you use body-parser and it is defined before your route.

npm install body-parser --save

and then include it before you define routes:

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

app.use(bodyParser.json());

app.post('/vote', function(req, res) {
   var id = req.body.id;
   var count = req.body.count;

   console.log("id: " + id);
   console.log("count: " + count);

   res.sendStatus(200);
   res.end();
});
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda