我目前正在努力讓用戶的會話根據客戶端的更新請求進行更新。這里的想法是在更新成功后立即將更新的用戶資料顯示給客戶端。為此,我使用會話來存盤資料,而不必每次重繪 都向資料庫發出 get-request。
我的問題是,每當用戶更新自己時,會話仍然保持登錄后檢索到的先前值,盡管我將其設定為新值。因此 updateMyProfile 請求不會保存會話中的資料。這是我用我的 Authenticate 請求測驗的東西,它在重繪 時呼叫以檢索 currentUser 的用戶資料
/服務器
app.use(
session({
key: "someID",
secret: "someSecret", //Normally this has to be long and complex for security
resave: false,
rolling: true,
saveUninitialized: false,
cookie: { //How long will the cookie live for?
expires: 60 * 60 * 1000, //Expires after one hour
}
}));
app.patch('/updateMyProfile', verifyJWT, async(req, res) => {
const name = req.body.name;
const email = req.body.email;
const phoneNr = req.body.phoneNr;
const id = req.body.id;
var updated = "UPDATE users set name = ?, email = ?, phoneNr = ? WHERE id = ?;";
var retrieved = "SELECT * FROM users WHERE id = ?;";
db.query(updated, [name, email, phoneNr, id],
(err, result) => {
if (err) {
res.send({message: err}) //Sending error to front-end
console.log(err);
}
if (result) {
db.query(retrieved, id,
(err, resultRetrieved) => {
if (err) {
res.send({message: err}) //Sending error to front-end
console.log(err);
} else {
req.session.user = resultRetrieved; //Session is updated to contain new data!
res.send({user: resultRetrieved, message: "Update succesful!"});
console.log("User is now: " req.session.user[0].name);
res.end();
}
})}
});
});
//通過UseEffect函式在客戶端每次重繪 時呼叫此方法
app.post('/authenticate', (req, res) => { //An endpoint for user-auth
const token = req.body.token;
const userSession = req.session.user;
jwt.verify(token, "jwtSecret", (err, decoded) => {
if (err) {
res.send({auth: false, user: "No valid token!"});
console.log('No valid token');
}
else if (userSession) { //Verified user! < ----------------->
res.send({auth: true, user: userSession});
console.log(userSession[0].name ' is in!');
}
else { //Else if user is not verified, we return an empty object with rejected authentication
res.send({auth: false, user: 'No user session!'});
console.log('No user session');
}
})
});
這是來自客戶端的更新請求示例
const update = () => {
Axios.patch("http://localhost:3001/updateMyProfile", {name: name, email: email, phoneNr: phoneNr, id: id},
{headers: {"x-access-token": localStorage.getItem("token")}}
).then(
(response) => {
alert(response.data.message);
}
);
}
uj5u.com熱心網友回復:
問題
上面的代碼雖然在混合使用服務器端會話和客戶端會話 (JWT) 的方式上有點不尋常,但它并沒有不正確或損壞。
在這種情況下,問題出在客戶端,處理 cookie 的方式 - 這意味著更新似乎沒有應用于會話資料。
服務器正確設定了會話 cookie,并被客戶端接受,但未包含在進一步的請求中。這意味著未來的請求似乎具有不正確的會話資料,因為服務器將每個請求視為一個全新的請求,而沒有先前存在的會話。這個事實被隱藏了,因為 JWT 被用來驗證用戶是否登錄,而不是檢查服務器端會話。
解決方案
Axios 被用于在客戶端發出請求,請求未使用適當的 cookie 標頭發送。
要解決此問題,應為每個請求提供如下withCredentials選項:
Axios.patch(address, data, { withCredentials: true }).then(handleResponse);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/428894.html
標籤:javascript 节点.js 反应 表示 会议
