在java后端创建config文件
package com.zf.demo.config;import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;@Configuration public class CorsConfig implements WebMvcConfigurer {@Overridepublic void addCorsMappings(CorsRegistry registry) {// 覆盖所有请求registry.addMapping("/**")// 允许发送 Cookie.allowCredentials(true).allowedOrigins("http://localhost:8081") // 精确匹配前端地址// 放行哪些域名(必须用 patterns,否则 * 会和 allowCredentials 冲突).allowedOriginPatterns("*").allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS").allowedHeaders("*").exposedHeaders("*");}}
Cookie .allowCredentials(true) // 允许发送
.allowedOrigins("http://localhost:8081") // 精确匹配前端地址不然前端拿不到因为是地址不一样的
存入cookie
这里我是存入多个cookie
Cookie idCookie = new Cookie("id", result.getId().toString()); Cookie deptIdCookie = new Cookie("deptId", result.getDeptId().toString()); Cookie usernameCookie = new Cookie("username", username); // 2. 统一设置 Cookie 属性 List<Cookie> cookies = Arrays.asList(idCookie, deptIdCookie, usernameCookie); for (Cookie cookie : cookies) {cookie.setPath("/"); // 全站可用cookie.setMaxAge(60 * 60 * 24 * 7); // 7天有效期response.addCookie(cookie); }
前端发送了请求之后,我这里是登录然后存的cookie
打开前端开发者模式
那么从前端怎么取出来cookie呢
在vue中的methos方法中写入
在需要的地方去调用该方方法,将你需要查找的cookie对象名传进去