我的 Google 登录有问题。 我按照服务器端应用程序的 Google 登录中的步骤操作 完成所有这一步后,我有了在服务器上运行的 html 文件:
<!DOCTYPE html>
<html itemscope itemtype="http://schema.org/Article">
<head>
<link rel="stylesheet" href="theme.css">
<!-- BEGIN Pre-requisites -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="https://apis.google.com/js/client:platform.js?onload=start" async defer></script>
<!-- END Pre-requisites -->
<script>
function start() {
gapi.load('auth2', function() {
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID'
});
});
}
</script>
</head>
<body>
<button id="googleBtn">Connect</button>
<script>
$('#googleBtn').click(function() {
auth2.grantOfflineAccess().then(googleCallback);
});
</script>
<script>
function googleCallback(authResult) {
if (authResult['code']) {
console.log(authResult);
} else {
console.log(authResult);
}
}
</script>
</body>
</html>
第一部分工作得很好(我认为),当我单击按钮时,会弹出一个窗口,我选择一个帐户并获得一个代码。现在,我想要获取电子邮件和个人资料,因此我在 Nodejs 中发出此请求,以使用访问令牌交换代码。
var form = {
code: 'XXXXXXXXXXXX',
client_id: 'CLIENT_ID,
client_secret: 'CLIENT',
grant_type:'authorization_code'
};
var formData = querystring.stringify(form);
var contentLength = formData.length;
request({
headers: {
'Content-Length': contentLength,
'Content-Type': 'application/x-www-form-urlencoded'
},
uri: 'https://www.googleapis.com/oauth2/v4/token',
body: formData,
method: 'POST'
}, function (err, rep, body) {
console.log(err);
console.log(rep.statusCode);
console.log(body);
});
但是作为回应,我有这个
{
"error": "redirect_uri_mismatch",
"error_description": "Bad Request"
}
我不明白为什么,因为我在html文件的主要请求中没有使用任何redirect_uri。我尝试过一些情况,例如在控制台 API 上和请求中添加redirect_uri,但我得到了相同的结果...
你能帮我吗?
从客户端
auth2.grantOfflineAccess
进程,要在服务器上获取accessToken,您必须在请求参数中传递redirect_uri=postmessage
。
从你的例子来看:
var form = {
code: 'XXXXXXXXXXXX',
client_id: 'CLIENT_ID,
client_secret: 'CLIENT',
grant_type:'authorization_code',
redirect_uri: 'postmessage' // the line to add
};
您需要通过 console.developer.google.com 定义 Google 的回调网址
因此您需要按照以下步骤定义回调 URL:
完成了。
在后端解决方案是设置redirect_uri =“postmessage”!就是这样!