简体   繁体   中英

Can't get JSON data from client side

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?

You're resetting app here with:

var app = express();

Remove that line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM