'Can't read data in node.js from a Ajax POST request

I need help with a very simple problem, but which for some reason I can't solve. I have a ajax post request that send data to a node.js server. From the server side, data seems to be received, but I am not able to retrieve the data fields.

Extract from the Client side:

function validateUser() 
{   
      $.ajax({
      type: "POST",
      url: "/authAjax",
      data: {
        username: "myusr",
        password: "mypsw"
      },
      success: function( result ) {alert("OK");},
      error: function( result ) {alert("ERR");}
    });
}

Extract from the Server side (node.js):

app.post('/authAjax', function(req, res)
{
    req.on('data', function (chunk) {
        console.log(req.body);      // not working
        console.log(req.username);  // not working
        console.log(req.data);      // not working
        res.send("200");            
    });
});

The res.send("200"); is executed, but I have no chance to get the passed username and password values. Could someone give any hint here?



Solution 1:[1]

These were missing on node.js side:

app.use(express.urlencoded());  
app.use(express.json());

And the data are accessible with:

req.body
    

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 harlem