[英]post method error nodejs req.body is returns {}
使用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); })
您需要为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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.