4

I want to send JSON data from client side to server side.

Client side:

function send() {
    var formData = {
        firstname: $("#name").val(),
        lastname: $("#lastname").val()
    }

    console.log("sending: " + JSON.stringify(formData));

    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "/dat",
        data: JSON.stringify(formData),
        dataType: 'json',
        success: function(customer) {
            console.log(JSON.stringify(customer));
        },
        error: function(e) {
            alert("Error!")
            console.log("ERROR: ", e);
        }
    });
}

Server side:

app.post("/dat", function (req, res) {
    console.log(JSON.stringify(req.body)); // return undefined
    res.end(JSON.stringify({ "nine": 9, "ten": 10, "eleven": 11 }));
});

I tried everything, but JSON.stringify(req.body) return only undefined. Sending data from server to client side working just fine... Any suggestions?

JoshG
  • 5,443
  • 2
  • 25
  • 45
KoRaP CZ
  • 53
  • 6
  • 1
    I'm going to assume you're using Express. Have you installed [`body-parser`](https://www.npmjs.com/package/body-parser#installation)? See https://stackoverflow.com/a/24635296/965834 for usage example. – Jeto Feb 16 '19 at 12:45
  • @Jeto yes, I got that. I have this: `const bodyParser = require("body-parser");` and `app.use(bodyParser.json());` – KoRaP CZ Feb 16 '19 at 12:56
  • Are you sure you're doing that before defining routes? – Jeto Feb 16 '19 at 13:09
  • @Jeto yes, I am sure... I uploaded my code to gitlab: https://gitlab.com/JaroslavVond/nodejs/tree/master/NodeServer – KoRaP CZ Feb 16 '19 at 13:42

1 Answers1

2

You're resetting app here with:

var app = express();

Remove that line.

Jeto
  • 13,447
  • 2
  • 22
  • 39