axios response Set-Cookie 获取不到信息的情况,无法自动配置

1.  前端登录之后Set-Cookie为空

login =(form : any)=>{
login(form.username,form.password).then(response =>{
const id = response.data.id
console.log(response)
console.log("document cookie :"+document.cookie)
if (id ===1){
message.success(response.data.id)
console.log(response.request)
}else {
message.success(response.data.id)
}
})
}


后台打印

 

 

 可以看到,Set-Cookie 为空,document获取不到,是因为HttpOnly这个属性,后台默认为了防止攻击开启了这个属性,获取不到。可以通过设置这个属性

public SimpleCookie getRememberCookie() {
SimpleCookie cookie = new SimpleCookie(simpleCookie());
cookie.setMaxAge(100);
cookie.setHttpOnly(true);
return cookie;
}

但是开启又不安全
因此,在前后端分离的情况下,获取cookie通过设置axios自动添加Set-Cookie属性
const service = axios.create({
baseURL:"http://localhost:8092",
timeout:10000,
withCredentials:true//开启
})

这样还是不能自动访问后台,因为前后台分离存在跨域问题,所以在后台设置cookie的domain
@Bean
public SimpleCookie simpleCookie() {
SimpleCookie cookie = new SimpleCookie("websession");
cookie.setDomain("localhost:3000");//重点
return cookie;
}


忙活了一天,如果前后台分离的项目,通过domain和axios的全局设置两处实现。
 

 

posted @ 2021-05-28 15:27  李悠然  阅读(5350)  评论(0编辑  收藏  举报