使用Glitch时Google登录按钮正常但页面跳转出现HTTP 405错误
问题排查与解决方案
错误根源
HTTP 405错误是因为Google登录完成后会以POST请求方式向data-login_uri指定的地址发送认证凭证,但你设置的https://nothingbuttylerplus.glitch.me/user/dashboard.html是静态HTML页面,Glitch的静态文件服务器只支持GET请求,无法处理POST请求,因此返回"Method Not Allowed"错误。
修复方案
方案1:前端直接处理登录(无需后端)
移除data-login_uri配置,改用前端回调函数接收Google返回的凭证,验证后再跳转到dashboard页面。修改后的代码如下:
<!--sign in with google--><!--popup sign in--> <div id="g_id_onload" style="display: inline-block; margin-right: 10px" data-client_id="531378190318-0blp8d27s3jk91t621gbijg5odlucekb.apps.googleusercontent.com" data-context="sign" data-ux_mode="popup" data-callback="googleLogin" <!-- 替换为前端回调 --> data-itp_support="true"> </div> <!--end of popup sign in--><!--button sign in--> <div class="g_id_signin" data-type="standard" data-shape="square" data-theme="outline" data-text="signin_with" data-size="medium"> </div> <i>(Note: The Google sign in button hasn't been working, so please use another application to sign in.)</i><br><!--end of button sign in--><!--end of sign in with google--><!--end of <!-- 👇 scripts --> <script src="https://accounts.google.com/gsi/client"></script> <script> function googleLogin(response) { console.log(response); const userInfo = parseJwt(response.credential); console.log(userInfo); // 验证凭证后跳转 window.location.href = '/user/dashboard.html'; } function parseJwt(token) { var base64Url = token.split('.')[1]; var base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/'); // 修复charCodeAt拼写错误,并返回解析后的用户信息 var jsonPayload = decodeURIComponent(atob(base64).split('').map(function (c) { return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2); }).join('')); return JSON.parse(jsonPayload); } </script> <!--end of 👆 scripts--> <!--end of sign in with google-->
方案2:后端处理POST请求(推荐用于生产环境)
如果需要在后端验证Google凭证的合法性,可在Glitch项目中添加Node.js/Express后端:
- 在项目根目录创建
server.js,添加以下代码:
const express = require('express'); const app = express(); const { OAuth2Client } = require('google-auth-library'); const client = new OAuth2Client('你的Client ID'); // 处理Google登录的POST请求 app.post('/auth/google', async (req, res) => { const { credential } = req.body; try { const ticket = await client.verifyIdToken({ idToken: credential, audience: '你的Client ID' }); const payload = ticket.getPayload(); // 验证通过,重定向到dashboard res.redirect('/user/dashboard.html'); } catch (error) { // 验证失败,跳转到登录页 res.redirect('/login.html'); } }); // 托管静态文件 app.use(express.static('public')); app.use(express.urlencoded({ extended: true })); app.use(express.json()); const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
- 修改前端代码的
data-login_uri为后端路由:
data-login_uri="https://nothingbuttylerplus.glitch.me/auth/google"
- 在Glitch项目的
package.json中添加依赖:
{ "dependencies": { "express": "^4.18.2", "google-auth-library": "^9.0.0" } }
额外注意点
- 你的
parseJwt函数存在拼写错误:c.CharCodeAt应改为c.charCodeAt,且缺少返回语句,已在方案1中修正。 - 生产环境务必在后端验证Google凭证,避免前端伪造用户信息。
内容的提问来源于stack exchange,提问作者NothingButTyler
相关产品推荐
相关产品推荐

