使用cURL或Postman时,一切都可以正常使用
curl -d 'username=Johny Sample&title=My First Post&description=We want some help cleaning up after the hurricane&postID=Johny Sample_1' http://localhost:3000/NewPost

请求结果
{"posterID":"Johny Sample","title":"My First Post","description":"We want some help cleaning up after the hurricane"}

服务器结果
req.body == {
username: 'Johny Sample',
title: 'My First Post',
description: 'We want some help cleaning up after the hurricane',
postID: 'Johny Sample_1'
}

无法在浏览器中使用
**
function gatherData()
{
var retData ='title='+el("title").value+'';
retData +='&description='+el('description').value+'';
postID = 'Johny Sample_1';
return retData;
}
function save() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
a = xhttp.responseText;
}
};
xhttp.open("POST", "http://localhost:3000/NewPost", true);
var sendData = gatherData();
xhttp.send(sendData);
}

**
请求结果
空
服务器结果
{} {}
服务器端代码
app.post('/NewPost', function (req, res) {
console.log(req.body);
var post = {};
post.posterID = req.body.username;
post.title = req.body.title;
post.description= req.body.description;
post.ID = req.body.ID;
console.log(post);
res.send(post);
})

答案 0 :(得分:0)
您需要为POST
添加HTTP标头xhttp.open("POST", "http://localhost:3000/NewPost", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var sendData = gatherData();
xhttp.send(sendData);