0

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);
    }
});
WillardSolutions
  • 2,275
  • 4
  • 28
  • 33
codeBarer
  • 2,312
  • 4
  • 34
  • 64

1 Answers1

1

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

app.use(bodyParser.json());
mscdex
  • 93,083
  • 13
  • 170
  • 135