2017-07-15 116 views
0

我目前正在通过Angular2的一些教程。不幸的是,我的教程并未涵盖Spotify API现在需要授权。我已经在Spotify Dev Corner中设置了一个应用程序。我对我的Angular2-服务代码看起来像这样Angular2服务 - Spotify API授权与cors策略失败

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
import 'rxjs/add/operator/map'; 

@Injectable() 
export class SpotifyService { 
    private searchUrl: string; 
    private token: string; 
    private client_id = 'xxxx'; 
    private client_secret = 'yyyy'; 
    private redirect_uri = 'http://localhost:4200'; 
    private responseType = 'code'; 

    constructor(private _http:Http){ 

    } 

    authorize(){ 
     return this._http 
      .get('https://accounts.spotify.com/authorize?client_id=' + this.client_id + '&client_secret=' + this.client_secret + '&redirect_uri=' + this.redirect_uri + '&response_type=' + this.responseType) 
      .map(res => res.json()); 
    }  
} 

而且在我的组件构造看起来像这样

constructor(private _spotifyService:SpotifyService) { 
     this._spotifyService.authorize().subscribe(res => { 
      console.log(res); 
     }); 
    } 

现在我的问题是,我的应用程序运行时,我得到一个错误与交叉起源政策,让我有点困惑,我不确定在哪里正确设置标题。

XMLHttpRequest无法加载 https://accounts.spotify.com/authorize?client_id=xxxx&client_secret=yyyy&redirect_uri=http://localhost:4200&response_type=code。 请求的 资源上没有“Access-Control-Allow-Origin”标题。原因'http://localhost:4200'因此不允许 访问。

我已将redirect_uri添加到我的Spotify应用程序的开发人员角落中。也许你可以帮忙。 HTTP服务器上预先感谢和

问候克里斯

+0

https://stackoverflow.com/questions/33029349/getting-spotify-api-access-token-with-node-js-express-js/ 33031590#33031590和https://stackoverflow.com/questions/24914853/authentication-request-to-spotify-web-api-rejected/24920670#24920670和https://stackoverflow.com/questions/33188989/allowing-cors- jquery-post-requests-to-spotify-api-on-express-js-server/33198424#33198424和https://github.com/spotify/web-api-auth-examples可能是相关的 – sideshowbarker

+0

好吧,我做了一点进展。看起来你很难通过获取请求授权,但你必须使用url作为组件中的链接。我进入spotify页面,在那里我被要求接受我的帐户和我的应用程序之间的连接。所以我唯一的问题是,我重新定向后。我如何访问我的组件中的响应数据?解决这个问题之后,我会在这里再次发布完整的代码作为答案 – Chris

回答

0

分享标题,如:nginx的,阿帕奇。

您需要阅读有关CORS政策。

需要共享的方法 - 选项,GET,POST例如

+0

令我困惑的是,cors头文件被设置在服务器上,所以在spotify中,对于我来说api会阻止这一点是没有意义的,但是在我注意到我注意到的回复中,您必须使用网址作为链接,并在接受Spotify帐户和应用程序之间的连接后,相应地重定向。我仍然唯一缺少的是我重新定向后在哪里找到该令牌 – Chris

+0

你想做什么? –