1.前端配置
const _axios = axios.create({
baseURL: 'http://localhost:8080',
withCredentials: true
})
前端这里我写成开始写成了127.0.0.1的形式,导致cookie一直不一致,需要改成 http://localhost
2.后端配置
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;
@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
// 允许跨域访问的路径
registry.addMapping("/**")
// 允许跨域访问的源
.allowedOrigins("http://localhost:7070")
// 允许请求方法
.allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")
// 预检间隔时间
.maxAge(168000)
// 允许头部设置
.allowedHeaders("*")
// 是否发送cookie
.allowCredentials(true);
}
}
后端代码
@PostMapping("a6set")
public String a6set(HttpSession session , HttpServletRequest request) {
System.out.println("=============================");
System.out.println(session.getId());
System.out.println(request.getSession().getId());
session.setAttribute("name", "张三");
System.out.println("set");
return "post request";
}
@PostMapping("a6get")
public String a6get(HttpSession session, HttpServletRequest request) {
System.out.println("=============================");
System.out.println(session.getId());
System.out.println(request.getSession().getId());
Object name = session.getAttribute("name");
System.out.println("get" + name);
return "post request";
}