2014-03-26 144 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; 
     } 
    }) 
相关问题