[英]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.