Reputation: 6347
I'm getting the following error when I try to get json response from a Spotify API call:
XMLHttpRequest cannot load https://api.spotify.com/v1/search?query=eminem&offset=0&limit=20&type=artist&market=US. Request header field Access-Token is not allowed by Access-Control-Allow-Headers in preflight response.
I have registered my app and used the code here (authorizaton code) https://github.com/spotify/web-api-auth-examples to generate Access token against my client_id
with redirect_url
set to http://localhost:8888/callback
.
I tried using this access token in my Angular service in the following way:
import { Injectable } from '@angular/core';
import {Http, Response, Request, RequestOptions, RequestOptionsArgs, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
const headers = new Headers({ 'Access-Token': 'My-Access-Token' });
let options = new RequestOptions({ headers: headers });
@Injectable()
export class ServicesService {
private searchUrl: string;
constructor(private _http: Http) { }
searchMusic(str: String, type='artist'){
this.searchUrl = 'https://api.spotify.com/v1/search?query='+str+'&offset=0&limit=20&type='+type+'&market=US'
return this._http.get(this.searchUrl, options)
.map(res=>res.json());
}
}
But as mentioned above its giving me the error. Any help would be appreciated.
Upvotes: 2
Views: 1287
Reputation: 1692
Altough I'm not familiar with the Spotify API this looks like the OAuth2 Implicit Grant Flow which uses the bearer token scheme.
As stated in RFC 6750 the token has to be transmitted in the Authorization
-Header.
When sending the access token in the "Authorization" request header field defined by HTTP/1.1 [RFC2617], the client uses the "Bearer" authentication scheme to transmit the access token.
For example:
GET /resource HTTP/1.1
Host: server.example.com
Authorization: Bearer mF_9.B5f-4.1JqM
[...]
Clients SHOULD make authenticated requests with a bearer token using the "Authorization" request header field with the "Bearer" HTTP authorization scheme.
In your code, you are doing
const headers = new Headers({ 'Access-Token': 'My-Access-Token' });
and the error you get says that the Request header field 'Access-Token' is not allowed
.
Assuming the Spotify API adheres to the standard (I would be surprised if they didn't) your header should look like this:
const access_token = 'YourAccessToken'
const headers = new Headers({ 'Authorization': 'Bearer ' + access_token });
Upvotes: 1