gpt4 book ai didi

javascript - Angular 2 http post 作为空对象或在关键端发送

转载 作者:可可西里 更新时间:2023-11-01 16:36:19 24 4
gpt4 key购买 nike

我正在尝试将数据从 angular 2 发送到服务器端的 Node 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 依赖

最佳答案

我找到了答案,我使用了 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 可以从 angular 2 的 http 库中导入

关于javascript - Angular 2 http post 作为空对象或在关键端发送,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44358847/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com