从Spotfiy API请求令牌时获取415不支持的媒体类型

时间:2019-03-31 14:48:31

标签: angular token spotify http-status-code-415

我正在尝试从Spotify api请求令牌以在我的应用中使用。 但是我收到“ 415不支持的媒体类型”错误。

如何克服这个错误?

  1. 我已经在POSTMAN中尝试过了,它似乎工作正常。
  2. 我试图将内容类型从x-www-form-urlencoded更改为JSON,反之亦然,这无济于事。
getToken() {
  let clientId = "xxxxxxxxxxxxxxxxxxxxxxxxx";
  let clientSecret = "xxxxxxxxxxxxxxxxxxxxxx";
  let apiURL = "https://accounts.spotify.com/api/token";

  let headers = new HttpHeaders();
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
  headers.append('Authorization', 'Basic ' + btoa(clientId + ':' + clientSecret));

  let params = new HttpParams();
  params.append('grant_type', 'client_credentials');

  this.http.post(apiURL+ params, { headers })
    .subscribe((res: IToken) => {
      console.log('token: ', res.access_token);
      console.log('expires in (s):', res.expires_in);
      console.log('Object: ', res);
      this.token = res.access_token;
      this.expiration = new Date().getTime() / 1000 + res.expires_in;
      console.log('now: ', new Date().getTime() / 1000);
      console.log('expiration: ', this.expiration);
    });
}

请在Chrome控制台中查看图片以了解错误:

https://i.stack.imgur.com/9vLnm.png

https://i.stack.imgur.com/ZlSte.png

1 个答案:

答案 0 :(得分:0)

只是在黑暗中拍摄,您是否尝试过将标头直接传递到HttpHeaders()构造函数中?我已经看到实例化实例后尝试.append().set()标头时有时会发生奇怪的事情。

尝试从以下位置更改标题/参数代码:

let headers = new HttpHeaders();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
headers.append('Authorization', 'Basic ' + btoa(clientId + ':' + clientSecret));

收件人:

...

const encodedClient = btoa(`${clientId}:${clientSecret}`);

const headers = new HttpHeaders({
   'Content-Type': 'application/json',
   'Authorization': `Basic ${encodedClient}`
});

const params = new HttpParams({
   'grant_type': 'client_credentials'
});

...

我不保证这可以解决您的问题,但是从您的图片中我可以看到标题/参数没有显示,尝试尝试可能是一件好事。

希望您能正常使用!

如果您对事物的引用感兴趣,我过去曾使用Angular编写的侧项目使用Spotify API:SpotifyTelevision