在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對象名傳進去