Home > Software engineering >  nodejs req.body undefined in case of ajax post requests
nodejs req.body undefined in case of ajax post requests

Time:04-01

Strange issue and I have no explanation to that. I create ajax post request

 $.ajax({  
        type: "POST",  
        url: "/like",  
        data: {"topic": "123123"},  
        success: function(dataString) {               
            console.log('123123'); 
        }  
    }); 

Or like this:

var xhttp = new XMLHttpRequest(); 
xhttp.open("POST", "/like", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford"); 

on server side (NodeJs) I have simple code

app.post('/like', function (req, res) {
    console.log(req.body);
    res.status(201).send(' 1')
});

what I dont understand, is why I receive all the time undefined when I send ajax post request.

enter image description here

CodePudding user response:

You need to use a body parser, see: nodejs.dev/learn/get-http-request-body-data-using-nodejs

  • Related