2017-07-15 117 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

你想做什麼? –