Files
StudyNote/语言/Java/大三前/前端智慧之书.md
2026-02-13 23:38:38 +08:00

3.9 KiB
Raw Permalink Blame History

5.21

image-20250521172948347

在引入组件之后 发现挤在一起了

问题原因

在import './style.css' 似乎是css冲突 删掉即可

image-20250521173028623 image-20250521173102408

当然可以!以下是你今天遇到的 bug 和完整的排查 + 解决过程总结,我已经帮你整理成一份标准 Markdown 文档,适合放在项目文档或问题记录中使用:


🐞 前后端分离登录接口跨域问题排查记录Session / Cookie 登录)

📅 日期2025-05-26

👨‍💻 项目环境

  • 前端Vite + Vue3 + Axios
  • 后端Spring Boot
  • 登录机制:后端使用 HttpSession 存储用户登录状态,依赖 Cookie 携带 JSESSIONID

问题描述

前端调用后端 /user/current 接口时,即使已经登录,依然返回:

{
  "code": 40100,
  "data": null,
  "message": "未登录",
  "description": ""
}

在浏览器 DevTools 的 Network 面板中也看到了以下错误:

Access to XMLHttpRequest at 'http://localhost:8080/api/user/current' from origin 'http://localhost:5173' 
has been blocked by CORS policy: The value of the 'Access-Control-Allow-Credentials' header in the response is '' 
which must be 'true' when the request's credentials mode is 'include'.

🔍 问题分析过程

原因一:未设置 withCredentials: true

前端使用 Axios 时,没有携带 Cookie导致后端无法识别登录态。

// 修复方式:在 myAxios.ts 中添加以下配置
const myAxios = axios.create({
  baseURL: 'http://localhost:8080/api',
  withCredentials: true
});

后端虽然设置了 @CrossOrigin(origins = {"http://localhost:5173"}),但未开启允许携带凭证,导致浏览器拦截了响应 Cookie。

// 修复方式:加上 allowCredentials = "true"
@CrossOrigin(origins = {"http://localhost:5173"}, allowCredentials = "true")
@RestController
@RequestMapping("/user")
public class UserController {
    ...
}

原因三(间接):没有设置全局 CORS建议增强处理

为避免今后其他接口忘记设置 @CrossOrigin,可以在后端添加全局 CORS 配置:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOriginPatterns("http://localhost:5173")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowCredentials(true)
                .allowedHeaders("*");
    }
}

最终解决方案总结

步骤 操作
前端配置 Axios 添加 withCredentials: true
后端接口注解 给所有使用 Session 的接口(如 /login/current)添加 @CrossOrigin(..., allowCredentials = "true")
建议增强 后端添加全局 CorsConfig 类统一处理跨域
验证方式 登录后检查浏览器 Application > Cookies 是否存在 JSESSIONID,以及请求头是否携带 Cookie

🎉 效果验证

  • 登录成功后,后端返回 Set-Cookie
  • 浏览器保存了 JSESSIONID
  • 请求 /user/current 成功返回用户信息
  • 所有登录态相关接口恢复正常

如果你还需要我帮你生成 PDF / README 格式的文档、或者直接拷贝到项目里 docs/bug-fix-log.md,也可以告诉我!