cant get access token from google using angularjs

不打扰是莪最后的温柔 提交于 2019-12-06 07:32:52

I think if you were to compare the resulting request generated by angular and the one sent by postman you would spot the difference here. (check out fiddler to achieve this).

The object map your passing as the 'params' is mapped to a query string parameters however google is expecting this data in the request body. To do this then set this as the 'data' parameter. However by default angular will send this as json so we need to transform this before it is posted. that's the purpose of the transformRequest function. (see this link for explanation)

See rewritten code below.

$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; 
       }
    })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!