2012-03-18 122 views
1

我试图使用JavaScript获取Google APi的access_token,并且总是收到错误消息:invalid_request。有我的代码:Google Api get access_token请求返回invalid_request

var options = { 
    url: tokenURL, 
    type: "POST", 
    headers: { "Content-type": "application/x-www-form-urlencoded"}, 
    dataType: "json", 
    data: { 
     "code":successCode, 
     "client_id": clietId, 
     "client_secret": clientSecret, 
     "grant_type": "authorization_code", 
     "redirect_url": "urn:ietf:wg:oauth:2.0:oob" 
    }, 
    complete: function (e) { 
     alert(e.status); 
    }, 
}; 

$.ajax(options); 

我也尝试使用简单的HTML表单发出POST请求,它的工作原理。

<form method="post" action="https://accounts.google.com/o/oauth2/token"> 
<input name="code" type="text" value="##code##" /> 
<input name="client_id" type="text" value="##client_id##" /> 
<input name="client_secret" type="text" value="##client_secret##" /> 
<input name="grant_type" type="text" value="authorization_code" /> 
<input name="redirect_uri" type="text" value="urn:ietf:wg:oauth:2.0:oob" /> 

<input type="submit" /></form> 

我不知道什么是错误的JavaScript请求。我是否缺少一些参数或标题?

+0

尝试使用Firebug看着Net标签就看你从形式VS Ajax请求 – dldnh 2012-03-18 15:34:58

+0

我使用招试图发出请求之间的差别,并没有注意到,除了饼干 – pauliusnrk 2012-03-18 19:29:51

回答

0

它看起来像编码data(在第一个示例中)与内容类型不匹配。

data的编码似乎是application/json,但指定的内容类型是application/x-www-form-urlencoded。

您需要将data的编码更改为urlencoded。

data: "code=successCode&client_id=clientId&client_secret=clientSecret&grant_type=authorization_code&redirect_url=urn:ietf:wg:oauth:2.0:oob" 
+0

任何差别通过设置数据像你说的,请求甚至没有送出:'VAR选项= { \t \t \t网址: 'https://accounts.google.com/o/oauth2/token', \t \t \t类型: “POST”, \t \t \t标题:{“Content-type”:“application/x-www-form-urlencod编“}, \t \t \t数据类型: ”JSON“, \t \t \t数据: ”代码=代码&CLIENT_ID =的clientId&client_secret = clientSecret&REDIRECT_URI = myuri&grant_type = authorization_code“, \t \t \t完成:功能(E){ \t \t \t \t警报(E); \t \t \t \t alert(e.status); \t \t \t}, \t \t}; \t \t $ .ajax(options);' – erdomester 2016-09-22 07:02:07