Home > database >  Data in ajax call from React to Node server is undefined
Data in ajax call from React to Node server is undefined

Time:01-05

I'm trying to just send data from my React frontend to Node backend using jquery's ajax method. The api request is being received by Node, but the data is undefined.

React:

console.log("Making Node API call");
$.ajax({
    method: "POST",
    url: "test",
    data: {
       name: "John",
       place: "Alaska"
    }
}).done(function( msg ) {
    console.log(msg);
});

Node:

app.post("/test", (req, res) => {
    console.log("Request received");
    console.log(req.body);
});

Node prints "Request received", followed by undefined. It's still undefined if I log req instead of req.body.

CodePudding user response:

I have a few ideas:

  1. Try to parse the data to a string. If you want to send an HTTP request it should be formatted to the proper type eg. text (string) or JSON.

When data is an object, jQuery generates the data string from the object's key/value pairs unless the processData option is set to false source: https://api.jquery.com/jQuery.ajax/

Your data actually looks like that:

data: '{"name":"John","place":"Alaska"}'

Thats why express may some problems with parsing.

Reference: jQuery posting valid json in request body

  1. You have problem with express body parser configuration.
  • Related