Google OAuth2获取访问令牌时遭遇‘unsupported_grant_type’错误求助
Google OAuth2获取访问令牌时遭遇‘unsupported_grant_type’错误求助
我太懂这种卡住的憋屈感了!前端处理Google OAuth2的靠谱例子确实不多,碰到unsupported_grant_type这种模糊的错误真的头大,不过看你的代码,我发现了两个关键问题,应该能帮你解决:
1. 发送的数据格式不匹配
你已经正确设置了Content-Type: application/x-www-form-urlencoded,但犯了一个很容易忽略的错误:直接把JS对象data传给了xhr.send()。XMLHttpRequest不会自动帮你把JS对象转换成表单编码格式的字符串,Google的token端点根本识别不了你发过去的数据,这就是它报grant_type无效的核心原因。
2. 数据对象的语法错误
看你的data定义,client_id那一行末尾少了个逗号——这会导致JS解析失败,data对象本身就不合法,自然也没法正常发送请求。
修正后的代码
我把这两个问题都修复了,你可以直接替换试试:
function getToken(){ let credentials; // 修复语法错误:给client_id行末尾添加逗号 var data = { 'code': authCode, 'client_id': clientid, 'client_secret': clientsecret, 'redirect_uri': redirecturi, 'grant_type': 'authorization_code' }; const xhr = new XMLHttpRequest(); xhr.open("POST", "https://oauth2.googleapis.com/token"); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200){ credentials = JSON.parse(this.response); gapi.client.SetToken(credentials.access_token); } else { document.getElementById("error").innerHTML = this.readyState + " + " + this.response; } } // 把JS对象转换成符合要求的表单编码字符串 const formData = new URLSearchParams(data); xhr.send(formData); }
额外的重要安全提醒
⚠️ 绝对不要在前端代码里暴露client_secret!任何人都能通过查看页面源码拿到这个密钥,这会直接威胁你的OAuth应用安全。正确的做法是:把client_secret存到你的后端服务器,前端拿到authCode后,把authCode传给后端,由后端代为调用Google的token端点获取令牌,再把令牌返回给前端。
备注:内容来源于stack exchange,提问作者Gertrude
相关产品推荐
相关产品推荐

