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

Google认证在HTML/JS代码中失效问题排查求助

问题排查与修复步骤

1. 修正Google Client ID的meta标签格式

你的meta标签存在引号不匹配问题,会导致Google无法正确识别Client ID:

<!-- 错误写法 -->
<meta name="google-signin-client_id" content=key.com">

<!-- 正确写法,替换为你的完整Client ID -->
<meta name="google-signin-client_id" content="你的-client-id.apps.googleusercontent.com">

2. 修复fetch请求的语法错误

当前JSON.stringify("email"=profile.getEmail())是语法错误,需改为合法的对象格式:

// 错误写法
body: JSON.stringify("email"=profile.getEmail())

// 正确写法
body: JSON.stringify({ email: profile.getEmail() })

3. 添加Django所需的请求头

Django要求POST请求携带CSRF令牌,同时发送JSON数据需指定Content-Type:

fetch("/loginWithGoogle", {
    method: "POST",
    headers: {
        "Content-Type": "application/json",
        "X-CSRFToken": getCookie("csrftoken") // 需添加获取CSRF令牌的辅助函数
    },
    body: JSON.stringify({ email: profile.getEmail() })
})

在script标签内添加获取CSRF令牌的函数:

function getCookie(name) {
    let cookieValue = null;
    if (document.cookie && document.cookie !== '') {
        const cookies = document.cookie.split(';');
        for (let i = 0; i < cookies.length; i++) {
            const cookie = cookies[i].trim();
            if (cookie.substring(0, name.length + 1) === (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}

4. 处理fetch请求的响应与错误

添加响应处理逻辑,便于调试和后续页面跳转:

fetch("/loginWithGoogle", {
    // 保留之前的配置
})
.then(response => {
    if (!response.ok) {
        throw new Error('请求失败');
    }
    return response.json(); // 可根据后端返回格式调整为response.text()
})
.then(data => {
    console.log('登录成功:', data);
    // 这里可添加页面跳转逻辑,比如 window.location.href = "/主页路径";
})
.catch(error => {
    console.error('登录请求出错:', error);
});

5. 确保请求Email权限

若profile.getEmail()返回null,需在登录按钮上添加email权限范围:

<div class="g-signin2" data-onsuccess="onSignIn" data-scope="profile email" style="margin-left: 643px; border-radius: 205px; scale: 1.4; width: 200px; font-size: 23px;"></div>

6. 检查浏览器控制台报错

打开浏览器开发者工具(F12)的Console面板,查看是否存在JS语法错误或网络请求异常,这是快速定位问题的核心方式。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 06:15:35