2

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.

ElliotD
  • 23
  • 3
  • I would log out the entire request object and check other properties. Since you're using ajax it may be URL encoding the payload, causing the data to be located elsewhere in the req object. IIRC you can change it by specifying a property in the ajax call. – therealdakotal Jan 04 '23 at 15:19
  • 1
    Have you configured on nodejs middleware that will extract body from request. For example I am usually using this middleware for that: https://expressjs.com/en/resources/middleware/body-parser.html – Ivan Vasiljevic Jan 04 '23 at 15:30
  • 1
    @IvanVasiljevic Missing middleware was the issue. Using body-parser resolved it. Thanks – ElliotD Jan 04 '23 at 16:46

1 Answers1

0

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.