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
相关产品推荐
相关产品推荐

