【问题标题】:cant get access token from google using angularjs无法使用 angularjs 从谷歌获取访问令牌
【发布时间】:2014-05-04 21:29:00
【问题描述】:

我正在关注this guide 并尝试从 google api 获取访问令牌。我已经得到了一个授权码。所以我使用 angularjs 将 httprequest 发送到谷歌服务器。问题是我总是得到错误的请求答案。这是我的代码:

        $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 来测试我的参数,它正在使用邮递员。 那里的错误是因为此请求的身份验证码已过期,但它可以正常工作!

有人对这个问题有意见吗? 非常感谢!!

【问题讨论】:

  • 我使用服务器代码来获取我的令牌。我不认为你想把你的秘密放在客户端设备上。

标签: angularjs google-api access-token


【解决方案1】:

我认为,如果您将 angular 生成的请求与邮递员发送的请求进行比较,您会发现这里的差异。 (检查提琴手来实现这一点)。

您作为“参数”传递的对象映射被映射到查询字符串参数,但是谷歌在请求正文中期望此数据。为此,请将其设置为“数据”参数。然而,默认情况下,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; 
       }
    })

【讨论】:

    猜你喜欢
    • 2017-11-13
    • 2017-04-23
    • 2013-07-20
    • 1970-01-01
    • 2018-09-25
    • 2016-04-19
    • 2021-01-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多