2017-02-27 30 views
0

我想通過構建一個簡單的Spotify應用程序來學習角度2。設置標題時的角度2前導航問題

但不知何故我卡在身份驗證過程中。

我的問題是,當我嘗試發送一個HTTP POST設置爲https://accounts.spotify.com/api/token

 
let tokenUrl = 'https://accounts.spotify.com/api/token'; 

    let keyEncrypted = btoa(this.client_id + ':' + this.client_secret); 

    let authHeaders = new Headers(); 
    authHeaders.append('Content-Type', 'application/x-www-form-urlencoded'); 
    authHeaders.append('Authentication', 'Basic ' + keyEncrypted); 

    let options = new RequestOptions({headers: authHeaders}); 

    let body = 'code=' + authCode + '&grant_type=authorization_code' + '&redirect_uri=' + this.redirect_uri; 

    let jsonString = JSON.stringify({ 
     code: authCode, 
     grant_type: 'authorization_code', 
     redirect_uri: this.redirect_uri 
    }) 


    return this._http 
     .post(
      tokenUrl, 
      jsonString, 
      options 
     ).map(res => { 
      res.json(); 
      }) 

我得到一個預檢「迴應預檢要求未通過訪問控制檢查標題:否」訪問控制允許來源...

但是,當我從返回刪除頁眉像

 
return this._http 
     .post(
      tokenUrl, 
      jsonString // Header removed 
     ).map(res => { 
      res.json(); 
      }) 

飛行前檢查似乎已被繞過,但後來我得到一個媒體類型不允許的錯誤。

所以我很困惑,現在想知道: 1.爲什麼發送郵件w/o頭忽略飛行前檢查和發送後w /頭不? 2.設置標題並且未設置時,角度http發佈是否發送不同類型的請求?

很多謝謝。

+0

您正在使用的http:// localhost來訪問你的應用程序的角度?像spotify這樣的服務通常可以讓您使用來自請求可能來自的域以及處於開發模式時的「localhost」。 –

回答

0

你必須準確理解你應該如何從Spotify獲取令牌。但看你的代碼,我可以從看Spotify documentation此行

authHeaders.append('Authentication', 'Basic ' + keyEncrypted); 
告訴你

也許應該

authHeaders.append('Authentication', 'Bearer ' + keyEncrypted);

首先,嘗試和使用程序從Spotify的API獲取令牌如Postman或Curl,使用令牌發出請求,然後一旦您從API接收到數據,並且您對流程應該如何工作有清晰的瞭解,那麼請嘗試使用Angular2應用程序。

0

Here - 文本/普通標題不會觸發CORS預飛行。刪除內容類型標題將默認爲文本/純文本。

嘗試使用Chrome,並且在不安全模式下啓動它 - 在PowerShell中的例子是

& "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --user-data-dir="C:\Users\{yourusername}\AppData\Local\Google\Chrome\User Data\Default"