Valentin H
Valentin H

Reputation: 7448

Why is the body of request empty?

I'm using a pattern from another project for sending JSON-data to node. In the other project it works, in this project not. The req-object is valide, but the body is empty. Why?

Client-side:

json = { "auth_user_pkref": 2 }
        json.test_id = "ANCA"
        json.questions_count = 3
        json.right_answers = 2
        json.wrong_answers = 1
        json.seconds_spent = 180

        console.log('/api/answer/add', json);
        $.ajax({
            url: "/api/answer/add",
            type: "post",
            data: JSON.stringify(json),
            contentType: "application/json",
            success: function (data) {

            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log("ERROR, DB error");
            }
        });

Server-side:

router.post('/api/answer/add', function (req, res) {
    console.log('/api/answer/add: ', req.body)

Server-log:

/api/answer/add:  undefined

Upvotes: 0

Views: 152

Answers (1)

Mustafa Mamun
Mustafa Mamun

Reputation: 2661

    json = { "auth_user_pkref": 2 }
    json.test_id = "ANCA"
    json.questions_count = 3
    json.right_answers = 2
    json.wrong_answers = 1
    json.seconds_spent = 180

    console.log('/api/answer/add', json);
    $.ajax({
        url: "/api/answer/add",
        type: "post",
        data: json,
        contentType: "application/json",
        success: function (data) {

        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.log("ERROR, DB error");
        }
    });

Try this

Upvotes: 1

Related Questions