I'm making an app that makes a search after the artist name using spotify API and I am getting this error: 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.
spotify.service.ts
import { Injectable } from '@angular/core';
import { Http, Headers, Response } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class SpotifyService {
private searchUrl: string;
private client_id ='****************************';
private client_secret = '*********************************';
private access_token:string;
private encoded = btoa(this.client_id + ':' + this.client_secret);
constructor(private http: Http) { }
getToken(){
var params = ('grant_type=client_credentials');
var headers = new Headers();
headers.append( 'Authorization', 'Basic ' + this.encoded);
headers.append('Content-Type' , 'application/x-www-form-urlencoded');
return this.http.post('https://accounts.spotify.com/api/token', params , {headers : headers} )
.map(res=> res.json());
}
searchMusic(str: string, type='artist', token: string) {
console.log(this.encoded);
this.searchUrl = 'https://api.spotify.com/v1/search?query='+str+'&offset=0&limit=20&type='+type;
let headers = new Headers();
headers.append('Authorization', 'Bearer' + token);
return this.http.get(this.searchUrl, {headers: headers})
.map((res: Response) => res.json())
}
}
I want to display the results in search.component.html. This is the search.component.ts
import { Component, OnInit } from '@angular/core';
import { SpotifyService } from '../spotify.service';
import { Artist } from '../../../Artist';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
searchStr: string;
searchRes: Artist[];
constructor(private spotifyService: SpotifyService) { }
ngOnInit() {
}
searchMusic() {
this.spotifyService.getToken()
.subscribe(res => {
this.spotifyService.searchMusic(this.searchStr, 'artist', res.access_token)
.subscribe(res => {
this.searchRes = res.articles.items;
})
})
}
}
I've also tried to use this proxyUrl:
getToken(){
var params = ('grant_type=client_credentials');
const proxyUrl = "https://cors-anywhere.herokuapp.com/";
var headers = new Headers();
headers.append( 'Authorization', 'Basic ' + this.encoded);
headers.append('Content-Type' , 'application/x-www-form-urlencoded');
return this.http.post(proxyUrl + 'https://accounts.spotify.com/api/token', params , {headers : headers} )
.map(res=> res.json());
}
But I'm getting this error now: "Only valid bearer authentication supported".
P.S. I don't want to bypass the CORS or install any extensions!