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的全局設置兩處實現。
 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM