'Ajax Node JS POST/GET request works but doesn't send data

Trying to send a post request to express server, everything works except receiving the data, I tried to test using postman and Insomnia and everything including the data is working fine - my code work but not sending the data-. what could be a potential issue for not receiving the data-body?

Express server:

app.post('/ajax', function (req, res){
   console.log(req.body);
   console.log('req received');
});

Ajax (Jquery):

var jsonData = JSON.stringify({ "serviceCategory": 4, "availDate": 2 });
            $.ajax({
                url: "/ajax",
                type: 'POST',
                headers: {
                    'content-type': 'text/html; charset=utf-8',
                    'Access-Control-Allow-Origin': '*',
                },
                data: {
                    "Name": "John"
                },
                success: function (res) {
                    console.log(res);
                },
                error: function (jqXhr, textStatus, errorMessage) {
                    console.log(errorMessage)
                }
            });

I have tried many things (Stringify, I removed urlencodedparser, add remove header) with everything I add or remove it works on Insomnia but not my code.



Solution 1:[1]

I believe, you need to do to changes.

  1. Use JSON.parse() method to convert json string into json object and set that json object to your data property of ajax call.
$.ajax({
    url: "/ajax",
    type: 'POST',
    headers: {
        'content-type': 'text/html; charset=utf-8',
        'Access-Control-Allow-Origin': '*',
    },
    data: JSON.parse('{ "serviceCategory": 4, "availDate": 2 }'),
    success: function (res) {
        console.log(res);
    },
    error: function (jqXhr, textStatus, errorMessage) {
        console.log(errorMessage)
    }
});
  1. Use express.json() or bodyParser.json() to extract json data from request in express depending on your express version.

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

var app = express();

app.use(bodyParser.json());

app.post('/', function(request, response){
  console.log(request.body);      // your JSON
   response.send(request.body);    // echo the result back
});

app.listen(3000);

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 Heretic Monkey