什么是'内容类型':'application / x-www-form-urlencoded在http post方法

时间:2016-08-09 19:20:06

标签: angularjs http angular xmlhttprequest angular2-http

我仍然不知道如何在角度2中制作正确的http post方法,我在他们的官方网站上显示。

我的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)
    );

如果我使用浏览器,请直接输入网址(https://mydomain/v1.0/cms/playlists/aolon/us?name=asd&shortName=lalalal&method=POST&trustedUserId=myuserid),它会生成正确的回复。

enter image description here

但是当我正常地执行此操作时,我的控制台会出错,

{“response”:{“statusCode”:478,“statusText”:“错误的参数 - 名称”}}

enter image description here 有什么想法吗?

更新:我将我的代码更改为此内容并且有效,有人可以向我解释一下吗?

  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 )

1 个答案:

答案 0 :(得分:1)

我认为您需要为POST请求正确设置Content-Type标头:

  • 隐含(来自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 }); // <-------