我正在制作一个使用 spotify API 在艺术家姓名后进行搜索的应用程序,我收到此错误:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头存在请求的资源。因此,不允许访问源“ http://localhost:4200 ”。
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())
}
}
我想在 search.component.html 中显示结果。这是 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;
})
})
}
}
我也尝试过使用这个 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());
}
但我现在收到此错误:“仅支持有效的不记名身份验证”。
PS 我不想绕过 CORS 或安装任何扩展!