我有一個允許用戶登錄的 Spring Boot 后端。
當我使用郵遞員發送 json 有效負載以登錄用戶時,它會回傳正確的回應以及 JSESSION 的 cookie。
帶有回應和 cookie 的郵遞員詳細資訊
當我在 react (axios) 中發送有效負載時,我在任何地方都看不到 JSESSION 的 cookie,但回應仍然可以嗎?
const API_URL = "http://localhost:8080/api/auth/";
login(uniqueId: string, password: string) {
return axios.post(API_URL "login", JSON.stringify({
"uniqueId": uniqueId,
"password": password
}),
{
headers: {
'Content-Type': 'application/json',
'withCredentials': 'true'
}
})
.then(response => {
console.log(response);
return response;
}).catch(error => {
return error.response
});
}
帶有回應但沒有 cookie 的 Chrome 選項卡
uj5u.com熱心網友回復:
'withCredentials': 'true'應該在headers (請求配置檔案)之外
在您的情況下,它將是:
const API_URL = "http://localhost:8080/api/auth/";
login(uniqueId: string, password: string) {
return axios.post(API_URL "login", JSON.stringify({
"uniqueId": uniqueId,
"password": password
}),
{
withCredentials: true,
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
console.log(response);
return response;
}).catch(error => {
return error.response
});
}
另一種解決方案是使用引數創建實體 axios withCredentials: true (創建 axios 實體)。
const BASE_URL = "http://localhost:8080/api/";
const api = axios.create({
baseURL: BASE_URL,
withCredentials: true,
headers: {'Content-Type': 'application/json'}
});
然后你可以這樣做:
return api.post("/auth/login", JSON.stringify({
"uniqueId": uniqueId,
"password": password
})) .then(response => {
console.log(response);
return response;
}).catch(error => {
return error.response
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/467297.html
