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

Angular如何接收Spring Boot后端发送的Cookie并在请求中回传

会话管理中Angular与Spring Boot的Cookie交互方案

后端Spring Boot实现代码

创建Cookie的接口

用户提交用户名后调用该接口生成并返回Cookie:

@PostMapping("/addUser")
public User addUser(@RequestBody String name, HttpServletRequest request, HttpServletResponse response) {
    
    HttpSession getSession = (HttpSession) request.getAttribute("session");
    Cookie cookie = new Cookie("sessionId", getSession.getId());
    // 补充Cookie属性配置(建议添加)
    cookie.setPath("/");
    cookie.setHttpOnly(true);
    cookie.setMaxAge(3600); // 1小时过期
    response.addCookie(cookie);

    sessionService.addSession(getSession);

    String session = getSession.getId();
    System.out.println("Session id is " + session);
    User newUser = new User(name, session);
    userService.addUser(newUser);

    return newUser;
}

测试Cookie接收的接口

用于验证前端传来的Cookie:

@PostMapping("/noOfUsers")
public int userCount(HttpServletRequest request, HttpServletResponse response) {
    System.out.println(request.getSession().getId());
     Cookie[] cookies = request.getCookies();
     if (cookies != null) {
            for (Cookie cookie : cookies) {
              if (cookie.getName().equals("sessionId")) {
                 System.out.println(cookie.getValue());
              }
            }
          }

    return this.userService.noOfUser();
}

注意:原接口的@RequestBody String sessionId参数可以移除,因为Cookie会自动通过请求头传递,后端直接从request.getCookies()读取即可。


Angular端Cookie处理方案

Postman测试正常,但Angular默认不会自动处理Cookie,需按以下配置实现:

1. 请求时开启凭证携带

Angular的HttpClient默认不会携带Cookie,所有需要传递Cookie的请求都要添加withCredentials: true配置:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable({ providedIn: 'root' })
export class UserService {
  constructor(private http: HttpClient) {}

  // 提交用户名并接收Cookie
  addUser(name: string) {
    return this.http.post('/api/addUser', name, { withCredentials: true });
  }

  // 请求时自动携带Cookie
  getUserCount() {
    return this.http.post<number>('/api/noOfUsers', {}, { withCredentials: true });
  }
}

2. 跨域场景下的额外配置

如果前后端存在跨域(域名/端口不同),需同时配置后端Spring Boot允许跨域凭证:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://你的前端域名:端口") // 禁止使用*,需指定具体域名
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowCredentials(true); // 允许携带Cookie等凭证
    }
}

3. 手动读取Cookie(可选)

若业务需要手动获取Cookie值(仅非HttpOnly的Cookie可读取),可通过document.cookie解析:

getSessionId(): string | null {
  const cookieList = document.cookie.split('; ');
  for (const cookie of cookieList) {
    const [key, value] = cookie.split('=');
    if (key === 'sessionId') {
      return value;
    }
  }
  return null;
}

若Cookie设置了HttpOnly: true,该方法无法读取,但不影响请求自动携带Cookie。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:05:23