2014-03-26 85 views
2

我正在瀏覽this guide並試圖從google api獲取accses令牌。我艾倫得到了一個認證代碼。所以我使用angularjs發送httprequest到谷歌服務器。問題是我總是得到不好的請求答案。這是我的代碼:無法使用angularjs從谷歌獲取訪問令牌

 $http({ 
      method: 'POST', 
      url: 'https://accounts.google.com/o/oauth2/token', 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
      params : { 
       code   : '4/heMv6ozWwCxS5RyTzCgThAgxvRyk.oske-bNEGOUTOl05ti8ZT3YnwwH8iQI', 
       client_id  : GoogleAppInfo.clientId, 
       redirect_uri : GoogleAppInfo.redirect_uri, 
       client_secret : GoogleAppInfo.client_secret, 
       grant_type  : 'authorization_code' 
      }, 
      data :'Demo' //just data to apply the heaser 

     }). 
     success(function(data, status, headers, config) { 
      alert('secsses'); 
     }). 
     error(function(data, status, headers, config) { 
      alert('error'); 

     }); 

我已經使用PostMan chorme addon來測試我的參數,可以和它的工作的郵遞員。 那裏的錯誤是因爲這個請求的授權碼已過期,但它正在工作! enter image description here

有沒有人對這個問題有好感? 非常感謝!

+0

我使用服務器代碼來獲取我的令牌。我不認爲你想把你的祕密放在客戶端設備上。 –

回答

1

我想如果你要比較角度產生的請求和郵遞員發送的請求,你會發現這裏的區別。 (檢查小提琴手來實現這一點)。

傳入的對象映射爲'params'映射到查詢字符串參數,但是google在請求正文中期待這些數據。爲此,請將其設置爲「數據」參數。然而,默認情況下,angular會將其作爲json發送,所以我們需要在發佈之前對其進行轉換。這是transformRequest函數的目的。 (有關說明,請參見this link

請參閱下面重寫的代碼。

$http({ 
    method: 'POST', 
    url: 'https://accounts.google.com/o/oauth2/token', 
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
    data: { 
      code   : '4/heMv6ozWwCxS5RyTzCgThAgxvRyk.oske bNEGOUTOl05ti8ZT3YnwwH8iQI', 
      client_id  : GoogleAppInfo.clientId, 
      redirect_uri : GoogleAppInfo.redirect_uri, 
      client_secret : GoogleAppInfo.client_secret, 
      grant_type  : 'authorization_code' 
     } 
    transformRequest: function(data) { 
     var buffer = []; 
     for (var name in data) { 
      if (! data.hasOwnProperty(name)) { 
       continue; 
      } 
      var value = data[ name ]; 
      buffer.push(
         encodeURIComponent(name) + 
         "=" + 
         encodeURIComponent((value == null) ? "" : value) 
      ); 
     } 
      var source = buffer 
       .join("&") 
       .replace(/%20/g, "+"); 
      return source; 
     } 
    }) 
相關問題