第二次Fetch请求未携带首次请求设置的Cookie问题求助
核心问题是你的postData函数缺少跨域Cookie配置,导致登录请求返回的Cookie未被浏览器保存,后续GET请求自然无法携带验证所需的Cookie。
修复步骤
1. 修改postData函数,添加Cookie跨域配置
在postData的Fetch选项中加入credentials: "include",和getData保持一致:
async function postData(url = "", data = {}) { const response = await fetch(url, { method: "POST", mode: "cors", credentials: "include", // 新增此行,跨域时允许携带/保存Cookie headers: { "Content-Type": "application/json", }, body: JSON.stringify(data), }); return response.json(); }
2. 优化登录逻辑(可选,让异步代码更清晰)
用async/await替代嵌套的then,避免回调地狱,同时增加错误处理:
$("#login_form").submit(async function(e) { e.preventDefault(); const email = $('#username_login').val(); const password = $('#password_login').val(); try { const loginRes = await postData("http://localhost:4000/api/login", { email, password }); console.log("登录返回:", loginRes); // 建议根据实际返回值判断登录成功,比如loginRes.code === 200或loginRes.success if (loginRes) { const profileRes = await getData("http://localhost:4000/api/profile"); console.log("用户数据:", profileRes); } } catch (err) { console.error("请求异常:", err); } });
原因说明
跨域场景下,Fetch API默认不会发送或接收Cookie,必须显式设置credentials: "include":
- 登录请求(POST)设置后,浏览器才会保存服务器返回的
Set-Cookie - 后续的用户数据请求(GET)设置后,才会携带已保存的Cookie完成身份验证
内容的提问来源于stack exchange,提问作者user2399035
相关产品推荐
相关产品推荐

