Fetch API请求头未自动添加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
相关产品推荐
相关产品推荐

