【问题标题】:Getting 415 Unsupported Media Type when requesting Token from Spotfiy API从 Spotfiy API 请求令牌时获取 415 Unsupported Media Type
【发布时间】:2019-08-21 20:25:23
【问题描述】:

我正在尝试从 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

【问题讨论】:

  • 你能不能改成 this.http.post(apiURL+ params, headers) 并检查 spotify 想要接收的内容类型是 application/x-www-form-urlencoded 还是 application/json
  • 接受:application/json,text/plain,/ Content-Type:application/json。还是给415
  • 那么你应该更改为 application/json 而不是 application/x-www-form-urlencoded
  • 我做了,但它仍然给出 415 错误
  • 我的你把你的源代码上传到某个地方让我看看?

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


【解决方案1】:

只是在黑暗中开枪,您是否尝试过将标头直接传递给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'
});

...

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

希望你能成功!

如果您对事物的引用感兴趣,我过去曾将 Spotify API 用于一个用 Angular 编写的副项目:SpotifyTelevision

【讨论】:

    猜你喜欢
    • 2021-07-16
    • 1970-01-01
    • 2012-04-19
    • 2019-09-01
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多