I'm trying to build a basic login page with a dashboard using Express server and Nextjs. After the user logs in with proper credentials, they are authenticated and then redirected to the dashboard... Or that's what's supposed to happen at least. It seems that when Router.push("/Dashboard") is called, an improper request is made. However, if I just type http://localhost:3000/Dashboard into the address bar it works.
Get dashboard route
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)
})
Log in and redirect from client side
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));
};
Here is what the request looks like when I manually type http://localhost:3000/Dashboard into the address bar
And here is what the request looks like when router.push is called
Hope someone can help with this. Thanks.
Edit: I get these errors (and output) in the console while rediredirecting
CodePudding user response:
So I figured out the issue. It's because I was submitting a form without calling event.preventdefault(), which I think was making an improper fetch request (hence the error above), as well as reloading the page. The new working code for attemptLogin (the function I call on form submit) is
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();
});
};