【问题标题】:Angular 5 - HTTP Post x-www-form-urlencodedAngular 5 - HTTP Post x-www-form-urlencoded
【发布时间】:2018-08-18 16:01:58
【问题描述】:

所以我一直在学习 Angular,并且即将完成我的第一个端到端应用程序。该应用程序利用 Spotify 的公共 API 来搜索音乐和播放曲目预览。

我在编写 Http Post 方法时遇到问题。这个 post 方法返回 .json,其中包含一个访问令牌,我用它来访问和调用 API。我的 Post 方法在 Postman 中工作得很好,但我不知道如何在 Angular 中编写它。

这就是我在 Postman 中所拥有的:

POST /api/token HTTP/1.1
Host: accounts.spotify.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic Y2M5ZjgzZWM1NGRkNDVlYTg1NGEzZDdhNmRmOGU2ZjY6YjNhY2FkMDc4YjkxNDNlZTkwNzgxMzBlNGJiNDVjZTI=
Cache-Control: no-cache
Postman-Token: 8e3e0924-1ad7-97b4-3aee-533486854434

grant_type=client_credentials

该帖子完美运行并返回我需要的 access_token。

这就是我在 Angular 中所拥有的:

    constructor(private _http:Http) {
    this.clientSecret = "Y2M5ZjgzZWM1NGRkNDVlYTg1NGEzZDdhNmRmOGU2ZjY6YjNhY2FkMDc4YjkxNDNlZTkwNzgxMzBlNGJiNDVjZTI=";
    this.authURL = "https://accounts.spotify.com/api/token";
    let header = new Headers();
    header.append("Content-Type", "application/x-www-form-urlencoded");
    header.append("Authorization", "Basic " + this.clientSecret);
    this._http.post(this.authURL, "grant_type=client_credentials", {headers: header})
    .map(res => res.json())
    .subscribe(res => {this.authToken = res.access_token})
  }

我收到此错误:

Failed to load https://accounts.spotify.com/api/token: 
Response to preflight request doesn't pass access control check: 
No 'Access-Control-Allow-Origin' header is present on the requested 
resource. 
Origin 'http://localhost:4200' is therefore not allowed access.

显然听起来我缺少一个标题,但我认为这是我发布正文的方式:“grant_type=client_credentials”。此外,与它的类型有关:application/x-www-form-urlencoded

任何帮助将不胜感激,谢谢!

附:这是我的第一篇文章,希望一切正常。

【问题讨论】:

标签: angular http post spotify


【解决方案1】:

Content-Type无关。问题的关键是你必须指定你的Spotify APP的Redirect URIs。然后,这个URL,http://localhost:4200情况下,将被允许访问 Spotify 的 API 端点。详见Spotify Developer Doc

【讨论】:

  • 试过这个...通过控制台得到同样的错误。我认为这是我发送帖子正文部分的方式。不过感谢您的快速响应。
猜你喜欢
  • 2012-07-02
  • 2020-04-21
  • 2021-09-28
  • 1970-01-01
  • 1970-01-01
  • 2013-12-20
  • 2017-09-22
  • 2014-03-30
  • 1970-01-01
相关资源
最近更新 更多