So I've been learning Angular and am just about finished with my first end to end application. The app utilizes Spotify's public API to search music and play previews of tracks.
I am having an issue with writing my Http Post method. This post method returns .json that includes an access-token that I use to access and make get calls to the API. My Post method works just fine in Postman but I can't figure out how to write it in Angular.
This is what I have in 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
That post works perfectly and returns the access_token I need.
This is what I have in 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})
}
I get this error:
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.
Obviously sounds like I'm missing a header but I think it's the way I am posting the body: "grant_type=client_credentials". Also, something to do with the fact its of type: application/x-www-form-urlencoded
Any help would be much appreciated, thanks!
P.S. This is my first post, I hope everything is formatted okay.