我仍然不知道如何在 Angular 2 中制作正确的 http 发布方法,我按照他们在官方网站上显示的那样做了。
我的 api.service.ts 中有这个函数 createNewPlaylist
createNewPlaylist(stDate: string, etDate: string, playlistTitle: string, shortTitle: string): Observable<any> {
/**some code here **//
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.post(`https://cmsapi-dev.b2c.on.aol.com/v1.0/cms/playlists/${this.g_app}/${this.g_region}?trustedUserId=myuserid`,
JSON.stringify({
name: playlistTitle,
shortName: shortTitle,
}), options);
}
我的组件中有这个功能
createNewPlaylist(stDate: string, etDate: string, playlistTitle: string, shortTitle: string):any {
this.apiService.createNewPlaylist(stDate, etDate, playlistTitle, shortTitle)
.map(res => console.log(res))
.subscribe(
data => console.log(data),
error => console.log(error)
);
如果我使用浏览器,直接输入 url ( https://mydomain/v1.0/cms/playlists/aolon/us?name=asd&shortName=lalalal&method=POST&trustedUserId=myuserid ),它会生成正确的响应。
但是当我正常操作时,我的控制台出现错误,
{"response":{"statusCode":478,"statusText":"Bad argument - name"}}
更新:我将我的代码更改为此并且它有效,有人可以向我解释吗?
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this.http.post(`https://cmsapi-dev.b2c.on.aol.com/v1.0/cms/playlists/${this.g_app}/${this.g_region}/?trustedUserId=myuserid`,
`name=${playlistTitle}&shortTitle=${shortTitle}`, options )
最佳答案
我认为您需要为您的 POST 请求正确设置 Content-Type
header :
隐含地(来自 RC2)
return this.http.post(`https://cmsapi-dev.b2c.on.aol.com/v1.0/cms/playlists/${this.g_app}/${this.g_region}?trustedUserId=myuserid`, { name: playlistTitle, shortName: shortTitle, });
明确地
let headers = new Headers(); headers.append('Content-Type', 'application/json'); // <------ return this.http.post(`https://cmsapi-dev.b2c.on.aol.com/v1.0/cms/playlists/${this.g_app}/${this.g_region}?trustedUserId=myuserid`, JSON.stringify({ name: playlistTitle, shortName: shortTitle, }), { headers }); // <-------
关于angularjs - 'Content-Type' : 'application/x-www-form-urlencoded do in http post method 是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38858797/