You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用JavaScript实现Google登录时出现空白页面问题求助

解决Google登录流程中页面空白的问题

核心问题:冲突的登录配置

你同时设置了data-login-uri和自定义handleCredentialResponse回调,这会导致Google Sign-In SDK自动发起表单提交到指定的login地址,触发页面跳转空白,直接覆盖了你自定义的fetch逻辑。


具体修复步骤

  1. 移除data-login-uri配置
    从g_id_onload元素中删除data-login-uri属性,确保SDK只执行你自定义的回调函数,不会自动跳转页面。

  2. 确保客户端ID一致
    检查<meta name="google-signin-client_id">和g_id_onload中的data-client_id完全相同,避免因ID不匹配导致的验证失败。

  3. 增强fetch错误处理
    后端可能返回非JSON格式的错误响应,直接调用response.json()会抛出异常,需要先检查响应状态:

    .then(response => {
        console.log("Received response from server");
        if (!response.ok) {
            throw new Error(`HTTP error! Status: ${response.status}`);
        }
        return response.json();
    })
    
  4. 验证后端CORS配置
    确保后端允许前端的Origin(比如你当前页面的域名或http://localhost:xxxx),否则fetch请求会被浏览器拦截,导致流程中断。

  5. 检查浏览器控制台日志
    打开浏览器开发者工具(F12),查看Console和Network标签:

    • Console里的报错信息能直接定位代码问题
    • Network标签可以查看Google token请求和后端接口请求的状态码、响应内容

修改后的完整代码示例

{% block content %}
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="referrer" content="strict-origin-when-cross-origin">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="google-signin-client_id" content="你的客户端ID">
    <title>Google Sign-In with JWT</title>
    <script src="https://accounts.google.com/gsi/client" async defer></script>
</head>
<body>
    <h1>Google Sign-In</h1>
    
    <div id="g_id_onload"
         data-client_id = "你的客户端ID"
         data-callback ="handleCredentialResponse"
         data-auto_prompt ="false">
    </div>
    
    <div class="g_id_signin"
         data-type="standard"
         data-size="large"
         data-theme="outline"
         data-text="sign_in_with"
         data-shape="rectangular"
         data-logo_alignment="left">
    </div>

    <script>
        console.log("Current origin:", window.location.origin);

        function handleCredentialResponse(response) {
            console.log("Received response from Google Sign-In");
            const idToken = response.credential;
            console.log("ID Token:", idToken);

            fetch('http://127.0.0.1:8000/user/login/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: JSON.stringify({ token: idToken }),
                credentials: 'include'
            })
            .then(response => {
                console.log("Received response from server");
                if (!response.ok) {
                    throw new Error(`Server returned status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                if (data.access) {
                    console.log("JWT Token:", data.access);
                    localStorage.setItem('jwt', data.access);
                    alert('Login successful!');
                } else {
                    console.error("Login failed:", data);
                    alert('Login failed!');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred during login');
            });
        }

        window.onload = function() {
            console.log("Page loaded. Google Sign-In should initialize soon.");
        };
    </script>
</body>
</html>
{% endblock %}

内容的提问来源于stack exchange,提问作者Shashank

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 05:34:56