我正在创建一个angular2应用程序,其中在服务中使用http来POST
调用mongoDB
。
当我POST
第一次拨打电话时,它工作正常,即条目已正确插入数据库中,但是当我第二次发送数据时,则未插入。
如果我是在第一次插入后重新加载页面,则其工作正常。
我进行了一些调试,发现在第二个请求中我req.body
是空白的。
这是我的代码:
page.service.ts
savePage(page: Object) {
this.headers.append('Content-Type', 'application/json');
let url = this.baseUrl+'/pm/pages/';
let data={};
data["data"]=page;
console.log(data); //this is printing both times correctly
//on second request data is blank where as it works correctly for first time
return this.http.post(url, JSON.stringify(data),{headers: this.headers})
.map((res: Response) => res.json()).catch(this.handleError);
}
这是节点服务中显示的req.body中的数据。
第一个请求:
body:{
data:{
name: 'wtwetwet',
desc: 'wetwetwetetwte',
isPublic: true,
createdBy: 'Bhushan'
}
}
第二个请求
body: {}
有输入吗?
我终于意识到,我的方法曾经在每次被调用时都设置了内容类型。
因此更改代码从:
savePage(page: Object) {
this.headers.append('Content-Type', 'application/json');
let url = this.baseUrl+'/pm/pages/';
let data={};
data["data"]=page;
return this.http.post(url, JSON.stringify(data),{headers: this.headers})
.map((res: Response) => res.json()).catch(this.handleError);
}
至:
savePage(page: Object) {
this.headers=new Headers();
this.headers.append('Content-Type', 'application/json');
let url = this.baseUrl+'/pm/pages/';
let data={};
data["data"]=page;
return this.http.post(url, JSON.stringify(data),{headers: this.headers})
.map((res: Response) => res.json()).catch(this.handleError);
}
为我做了把戏。实际上,在进行rest调用时,我们只需要设置一次标头,但是在我的代码中已经设置了标头,因此创建新的Headers Object帮助我清除了之前设置的所有配置。
感谢您的帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句