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

如何获取会话数据?Svelte前端请求返回401状态码问题排查

解决Svelte前端获取会话数据时的401未授权问题

核心原因

前端fetch请求默认不会携带Cookie凭证,导致后端无法识别用户会话,返回401状态码。

分步解决方案

1. 修改前端fetch请求,携带会话凭证

在你的check函数中,给fetch添加credentials: 'include'选项,让浏览器自动携带目标域名的Cookie:

async function check() {
    try {
        const response = await fetch('http://localhost:8080/check', {
            credentials: 'include' // 新增这一行
        });
        if(response.ok) {
            const result = await response.json();
            if (result.message === "You are logged in!") {
                goto('/dashboard');
            } else {
                console.log('未检测到登录状态')
            }
        } else if(response.status === 401) {
            console.log('未授权,请先登录')
            // 可在此处跳转到登录页
            // goto('/login');
        }
    } catch (error){
        console.error('请求出错', error)
    }
}

2. 确认后端CORS配置的正确性

你的CORS配置已满足基础要求,需保持两个关键设置:

  • AllowOrigins必须指定具体前端域名,不能用通配符*(当前配置["http://localhost:5173"]是正确的)
  • AllowCredentials: true必须开启,这是跨域携带Cookie的必要条件

3. 检查会话Cookie的配置兼容性

当前会话存储配置适配本地HTTP开发环境:

  • HttpOnly: true:防止XSS攻击,配置正确
  • SameSite: http.SameSiteLaxMode:允许跨域请求携带Cookie,符合本地开发需求
  • Secure: false:本地HTTP环境无需开启,部署到HTTPS环境时需改为true

4. 验证后端接口的会话读取逻辑

确保后端/check接口正确读取并验证会话,示例代码(基于Golang sessions库):

func checkHandler(w http.ResponseWriter, r *http.Request) {
    // 读取会话,注意第二个参数为会话名称,需与登录时保持一致
    session, err := store.Get(r, "user-session")
    if err != nil {
        http.Error(w, "服务器错误", http.StatusInternalServerError)
        return
    }

    // 检查会话中是否存在登录标识(如userID)
    userID, exists := session.Values["userID"]
    if !exists || userID == nil {
        http.Error(w, "未授权", http.StatusUnauthorized)
        return
    }

    // 验证通过,返回登录状态
    w.Header().Set("Content-Type", "application/json")
    json.NewEncoder(w).Encode(map[string]string{"message": "You are logged in!"})
}

后续排查(若问题仍存在)

  • 打开浏览器开发者工具,在Application > Cookies下查看http://localhost:8080域名下是否存在会话Cookie
  • 在Network标签中查看/check请求的Request Headers,确认是否包含Cookie字段
  • 检查后端日志,确认会话是否被正确读取

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.22 21:13:24