post方法错误nodejs req.body返回{}

时间:2017-09-28 15:09:45

标签: javascript node.js api express curl

使用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);
	})




1 个答案:

答案 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);