我有一個登錄頁面,它向我的服務器發出請求,它設定會話 cookie 并重定向到儀表板頁面。在登錄頁面上,我可以在發送憑據后驗證 cookie 是否設定正確,并且當我手動單擊鏈接以在站點中導航時(如預期的那樣),它將持續存在。
但是,當我在登錄功能成功后嘗試自動重定向到儀表板時,我的 cookie 未設定,我無法弄清楚它去了哪里。我曾嘗試通過document.location/window.location使用不同的.href/ .path/.url欄位管理重定向,但在呼叫其中任何一個或重繪 頁面后 cookie 就消失了。
我正在使用127.0.0.1帶有 CORS 的自簽名 HTTPS(經過很多頭痛后,我不再收到 CORS 錯誤,所以我認為問題不存在,特別是因為我可以看到它在沒有重定向的情況下存在)。另外,我使用Svelte作為前端,使用Axum (Rust)作為后端,如果這很重要的話。
為什么在嘗試將用戶強制重定向到另一個頁面時,我的 cookie 會被“吃掉”?
請求方法:
await fetch('https://localhost:4000/users', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: `{ "email": "${email}", "password": "${await hash}" }`
});
// cookie exists if this line is removed
document.location.href = '/dashboard';
// cookie is gone when the new page loads
服務器配置(Axum):
let server = axum_server::bind_rustls(
SocketAddr::from(([127, 0, 0, 1], 4000)),
tls_config,
)
.serve(
Router::new()
.route("/", get(root))
.layer(
CorsLayer::new()
.allow_headers([
header::CONTENT_TYPE,
header::CONTENT_LENGTH,
header::COOKIE,
header::SET_COOKIE,
])
.allow_methods([
Method::GET,
Method::HEAD,
Method::OPTIONS,
Method::DELETE,
Method::POST,
])
.allow_origin([
HeaderValue::from_str("http://127.0.0.1:3000").unwrap(),
HeaderValue::from_str("https://127.0.0.1:3000").unwrap(),
])
.allow_credentials(true),
)
.into_make_service(),
);
回應標頭:
HTTP/2 200 OK
content-type: application/json
set-cookie: session=1234; Path=/; HttpOnly; SameSite=None; Secure
content-length: 26
access-control-allow-origin: https://127.0.0.1:3000
access-control-allow-credentials: true
vary: origin
vary: access-control-request-method
vary: access-control-request-headers
date: Tue, 07 Jun 2022 01:56:11 GMT
uj5u.com熱心網友回復:
我最終用電話代替了我fetch的電話axios,它現在按預期作業。我仍然不知道我是不是用錯了,但是這些看起來和我很像……
await fetch('https://localhost:4000/users', {
method: 'POST',
credentials: 'include',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: `{ "email": "${email}", "password": "${await hash}" }`
});
await axios.post('https://localhost:4000/users', {
email: email,
password: await hash,
}, {
withCredentials: true
});
如果有人能夠解釋有什么區別,我會非常感興趣:)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/489978.html
標籤:javascript http 饼干 锈 轴心
