codeBarer codeBarer - 3 months ago 11
jQuery Question

jQuery Post node being sent to Node JS body using POST

I'm not sure what I'm doing wrong but when I do an AJAX call using jQuery the
Node Express App doesn't get values passed to it. the output of the console log is "{}"

I tried curl and curl works just not jQuery request.

curl command:

curl -XPOST localhost:3000/upsert -d'{"test":"test"}'


Node JS excerpt

var bodyParser = require('body-parser');
var express = require('express');
var app = express();
app.use(bodyParser.urlencoded({extended : true}));

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


JQuery excerpt:

$.ajax({
type: "POST",
url: '/upsert',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: function () {
var payload = {};
payload["name"] = $("#exercise").val();
payload["reps"] = $("#reps").val();
payload["weight"] = $("#weight").val();
payload["date"] = $("#date").val();
payload["units"] = $('input[name=units]:checked').val();

return JSON.stringify(payload);
},
success: function (result) {
console.log(result);
},
failure: function (err) {
alert(err);
}
});

Answer

Since you're sending application/json, you will need the bodyParser.json() middleware:

app.use(bodyParser.json());
Comments