0

I have ajax code in below , i want to read data which is i am sending using ajax i want to read data in server side.

     $.ajax({
                    type: 'POST',
                     data: {hurl: "test data"},
                    contentType: 'application/json',
                    url: 'http://localhost:5000/hmap',
                    success: function(data) {
//                            console.log('success');
//                            console.log(JSON.stringify(data));

                        console.log(data);
                    }
                });
            });

below is my server side node js code

var hmapdata = [];
app.post('/hmap', function(req, res) {
    console.log(req.body);
    MongoClient.connect(url, function(err, db) {
        if (err)
            throw err;
        db.collection("heatmap").find().toArray(function(err, result) {
            if (err)
                throw err;
            hmapdata = result;

            db.close();
        });
    });
    setTimeout(function() {
        res.send(hmapdata);
    }, 1000);
});

1 Answers1

1

To send a JSON payload using jQuery Ajax, you must send a an actual JSON string, not a javascript object.

So you would need to do:

data: JSON.stringify({ hurl: "test data" })

enter image description here

This is what you're sending:

enter image description here

Now in your server, if you're using the body-parser middleware, the posted JSON will be available in req.body

app.use(bodyParser.json());

app.post('/hmap', function(req, res) {
    console.log(req.body); // req.body.hurl == "test data"
});

More details on: jQuery posting valid json in request body

Marcos Casagrande
  • 37,983
  • 8
  • 84
  • 98