0

我正在制作一个使用 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 或安装任何扩展!

4

2 回答 2

0

安装这个 chrome 扩展,它会让你绕过 CORS。在我的本地主机中使用 API 时,我经常使用它。 Chrome CORS 扩展

于 2018-09-27T11:10:43.807 回答
0
https://accounts.spotify.com/api/token

该 spotify 端点应该在后端使用。这就是为什么你有一个client_secret令牌。您使用这些凭据在后端发出请求并取回令牌。然后,您将该令牌发送到前端。

然后,在前端,您将该令牌用于其他端点,例如https://api.spotify.com/v1/设置了 CORS 标头以允许跨域请求。

例如:

var authToken = null;
fetch('http://yourserver.com/requestNewToken').then(token=>{
  authToken = token;
  //now use that token with your frontend requests like:
  searchMusic(this.searchStr, 'artist', authToken)
});

您在服务器上创建的某个端点在哪里http://yourserver.com/requestNewToken,您可以在其中进行调用https://accounts.spotify.com/api/token并返回令牌响应。

旁注,因为您client_secret现在已受到损害,您应该制作一个新的。

还要确保通读 Spotify 的开发人员帮助页面,例如客户端凭据流和整个授权页面,以便更好地理解发出请求的正确流模式。

于 2018-09-27T11:44:41.177 回答