【发布时间】: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
任何帮助将不胜感激,谢谢!
附:这是我的第一篇文章,希望一切正常。
【问题讨论】:
-
这是一个 CORS 问题,您需要从服务器而不是浏览器进行调用。 stackoverflow.com/questions/28389699/…
-
尝试使用 Node.js 构建服务器。希望这能解决问题。