codeBarer codeBarer - 1 year ago 86
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}));'/upsert',function(req, res){

JQuery excerpt:

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) {
failure: function (err) {

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download