Angular 2的http post是作为空对象或在密钥端发送的

我试图发送数据从angular2到节点js在我的angular码是服务器端

addCrib(data:any) { let bodyString = data; let headers = new Headers({ 'Content-Type': 'application/json' }); return this.http.post('http://localhost:8000/addcribs',data , {headers:headers}).map(res => res.json()).subscribe( data => console.log(data) ); } 

和在服务器端

 addcribs: function(req,res){ var x = req.body; console.log(x); // {} with application/json and { '{data....}':''} with application/x-www-form-urlencoded let crib = new Cribs({id:0, type:req.body.type,price:req.body.price,address:req.body.address,description:req.body.description,bedrooms:req.body.bedrooms,bathroom:req.body.bathroom,area: req.body.area,image:req.body.image}); crib.save(function(err,crib){ if(!err){ res.json({success:true}); } }) } 

当我console.log它在服务器端,当我使用contentType:application / json,当我使用contentType:application / x-www-form-urlencoded时,我得到一个空的对象{}我得到关键的一面的所有数据对象,例如。 {'{type:house}':''}我试图在客户端的数据上使用JSON.stringify,但没有帮助

注意我在服务器端使用cors依赖

我find了答案,我使用了content-Type:application / x-www-form-urlencoded

并用于:

 let urlSearchParams = new URLSearchParams(); urlSearchParams.append('type', data.type); urlSearchParams.append('bathrooms', data.bathrooms); let body = urlSearchParams.toString() 

urlSearchParams可以从http库以angular度2导入

既然我不能评论马尤姆·尤塞夫最后的评论,我正在写这个:

由于您正在处理JSON对象,并且想要将它们转换为编码的表单url,最好执行以下操作:

 const body = new URLSearchParams(); //The code below will take any JSON object into URLSearchParams variable, this way you won't need to keep assigning each value manually //value here refers to a typescript class or json object that you have Object.keys(value).forEach(key => { body.set(key, value[key]); }); 

然后,只需将body.toString()作为值发送回服务器,请确保json或类对象与服务器接受的内容匹配

在angular2中从@ angular / http导入URLSearchParams非常重要,因为URLSearchParams不会在Microsoft Edge / IE中定义,请参阅URLSearchParams浏览器的兼容性