我想从客户端向服务器端发送 JSON 数据。
客户端:
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);
}
});
}
服务器端:
app.post("/dat", function (req, res) {
console.log(JSON.stringify(req.body)); // return undefined
res.end(JSON.stringify({ "nine": 9, "ten": 10, "eleven": 11 }));
});
我尝试了所有方法,但是 JSON.stringify(req.body)
只返回 undefined
。从服务器向客户端发送数据工作正常......
有什么建议吗?
最佳答案
关于javascript - 无法从客户端获取 JSON 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54723146/