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

Fetch API请求头未自动添加Cookie导致403问题排查

问题:请求未自动携带Cookie导致403状态码

我遇到的问题是请求头中未添加Cookie,因此收到403状态码。具体来说,我正在实现一个系统,当用户打开页面时,会获取请求令牌并添加到HTML的<meta>标签中,同时存入document.cookie。用户登录时,下方的fetchSignIn请求因设置了credentials: "include"本应自动添加Cookie,但实际并未生效。我已参考相关示例,但不清楚实现哪里出错。

登录实现代码(面向对象)

class Login {
// 私有方法...

    fetchSignIn (obj, url) {
        console.log("Cookie ", document.cookie);
        fetch(url, {
            method: "POST",
            mode: "cors",
            credentials: "include",
            body: JSON.stringify(obj),
            headers: {
                "Content-Type": "application/json",
                "Authorization": "",
                "X-XSRF-TOKEN": getQSelector('meta[name="_csrf"]').content
            }
        })
        .then((response) => response.text())
        .then((data) => {
            console.log(data);
        })
        .catch((error) => {
            console.error('Error: ', error.message);
        });
    }
}

页面加载时获取令牌的代码

window.addEventListener("DOMContentLoaded", (e) => {
    _loadCSRF(CSRFDOMLOAD);
})

const _loadCSRF = (path) => {
    fetch(path) // GET 请求
    .then((response) => response.json())
    .then((data) => {
        console.log(data);
        document.cookie = data.headerName + "=" + data.token;
        getQSelector('meta[name="_csrf_header"]').setAttribute("content", data.headerName);
        getQSelector('meta[name="_csrf"]').setAttribute("content", data.token);
    })
    .catch((err) => console.error("Failed csrf fetch ", err));
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 00:45:57