我正在嘗試使用 Express 服務器和 Nextjs 構建一個帶有儀表板的基本登錄頁面。用戶使用正確的憑據登錄后,他們將通過身份驗證,然后重定向到儀表板......或者至少應該發生這種情況。似乎在呼叫 Router.push("/Dashboard") 時,提出了不正確的請求。但是,如果我只是在地址欄中鍵入 http://localhost:3000/Dashboard 它就可以作業。
獲取儀表盤路由
server.get('/Dashboard', checkSignIn, (req, res) => {
console.log("In dashboard")
if(req.session.page_views){
req.session.page_views ;
} else {
req.session.page_views = 1;
}
console.log("Page views: ", req.session.page_views)
return handle(req, res)
})
從客戶端登錄并重定向
const router = useRouter();
const attemptLogin = async (event: KeyboardEvent) => {
const username: string = event!.target!.username!.value;
const password: string = event!.target!.password!.value;
fetch("http://localhost:3000/SignIn", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ username, password }),
})
.then((res) => {
if (res.status === 200) {
console.log("Status is 200");
return router.push("/Dashboard");
}
})
.catch((err) => console.log("err is", err));
};
這是我在地址欄中手動鍵入 http://localhost:3000/Dashboard 時請求的樣子

這是呼叫 router.push 時請求的樣子

希望有人可以幫助解決這個問題。謝謝。
編輯:我在重定向時在控制臺中收到這些錯誤(和輸出)

uj5u.com熱心網友回復:
所以我想通了這個問題。這是因為我在沒有呼叫 event.preventdefault() 的情況下提交了一個表單,我認為這是一個不正確的獲取請求(因此出現了上面的錯誤),以及重新加載頁面。tryLogin 的新作業代碼(我在表單提交時呼叫的函式)是
const attemptLogin = async (event: KeyboardEvent) => {
event.preventDefault();
const username: string = event!.target!.username!.value;
const password: string = event!.target!.password!.value;
fetch("http://localhost:5000/SignIn", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({ username, password }),
})
.then((res) => {
if (res.status === 200) {
console.log("Status is 200");
return router.push("/Dashboard");
}
})
.catch((err) => {
console.log("err is", err);
event!.target!.reset();
});
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/390757.html
上一篇:在NestJs中使用連接閃存
下一篇:決議嵌套的Axios請求
