我尝试使用 JavaScript 获取 Google APi 的 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 请求有什么问题。我是否缺少一些参数或 header ?
最佳答案
看起来数据
的编码(在第一个示例中)与内容类型不匹配。
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"
关于javascript - Google Api获取access_token请求返回invalid_request,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9759532/