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

Vue3+SpringBoot获取登录用户信息遇CORS、空值问题解决

问题背景
  • 开发学校项目的「我的资料」页面,需支持修改个人资料(PUT 请求)、注销账号(DELETE 请求)
  • 技术栈:
    • 前端:TypeScript、Vue 3、Node.js、Axios
    • 后端:Java、Spring Boot Security、JWT
  • 现存问题:请求登录用户信息接口时返回 null、触发 CORS 拦截导致 Axios 请求失败,前端拿到异常响应后渲染 Vuetify 组件时页面崩溃。
现有问题代码

后端接口

@GetMapping("/user/me")
public String getMyUser(@CookieValue("jwtExample") String userToken) {
    return jwtUtils.getUserNameFromJwtToken(userToken);
}

Axios 配置

const axiosApi = axios.create({
  baseURL: `http://localhost:8080/api/auth`,
  timeout: 1000,
  headers: { "Content-Type": "application/json" },
});

getMyUser(): Promise<AxiosResponse<string>> {
    return axiosApi.get("/user/me");
}

前端数据渲染逻辑

paintMyProfileInfo() {
  this.$store
    .dispatch("getMyData")
    .then((response) => (this.user = response.data))
    .catch((error: AxiosError) => console.log(error));
},
修复方案

1. 解决CORS拦截、Cookie拿不到的问题

核心原因是跨域场景下Axios默认不携带Cookie,Spring Boot默认CORS配置也不允许接收跨域携带的Cookie,导致后端读不到jwtExample字段,解析结果为null。

  • 后端新增CORS配置,注意不要用通配符*匹配允许源,必须明确写前端运行地址,开启允许携带凭证:
@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
                .allowedOrigins("http://localhost:5173") // 替换为本地前端实际启动地址
                .allowedMethods("GET","POST","PUT","DELETE","OPTIONS")
                .allowCredentials(true)
                .allowedHeaders("*")
                .maxAge(3600);
    }
}
  • 修改Axios全局配置,开启跨域携带Cookie,同时调大超时时间避免本地调试超时:
const axiosApi = axios.create({
  baseURL: `http://localhost:8080/api/auth`,
  timeout: 10000,
  headers: { "Content-Type": "application/json" },
  withCredentials: true // 关键配置,跨域请求自动携带Cookie
});
  • 检查Spring Security配置,确保/api/auth/user/me接口不会被拦截重定向到登录页,JWT认证过滤器正确从Cookie中读取token解析用户身份。

2. 优化后端接口逻辑

给@CookieValue注解加required = false配置,避免未携带Cookie时直接抛出400错误,同时建议直接返回完整用户信息而非仅用户名,减少前端额外请求:

@GetMapping("/user/me")
public UserVO getMyUser(@CookieValue(value = "jwtExample", required = false) String userToken) {
    if (userToken == null || !jwtUtils.validateJwtToken(userToken)) {
        throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "用户未登录");
    }
    String username = jwtUtils.getUserNameFromJwtToken(userToken);
    return userService.getUserByUsername(username); // 查询并返回用户完整信息视图对象
}

3. 解决页面渲染崩溃问题

崩溃原因是请求失败时user变量为null/undefined,Vuetify组件渲染时直接访问user下的属性触发JS报错。

  • 初始化user变量时给和返回字段匹配的默认空值,不要初始化为null/undefined
  • 模板渲染时加可选链或者加载判断,比如用v-if="user"包裹资料组件,或者字段渲染写{{ user?.username }}
  • 检查Vuex中getMyData的action逻辑,确保正确return接口响应结果,不要在action内部吞掉响应导致dispatch拿不到返回值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.01 21:09:58