I'm making a node.js app with express and I'm trying to make a login form for my users, I want to have a Javascript file with a fetch() call to make a POST request to my API to login the user, but I can't seem to redirect the user after a successful login, it stays on the same page, I can log the result from fetch but can't redirect.
Here's the server code (authentication is working fine, just the redirect isn't):
router.post('/users/login', login.none() , async (req, res) => {
try {
const user = await User.findByCredentials(req.body.email, req.body.password)
const token = await user.generateAuthToken()
res.cookie('access_token', 'Bearer ' + token, {
expires: new Date(Date.now() + 8 * 3600000) // cookie will be removed after 8 hours
})
.redirect('/users/me')
} catch (error) {
res.status(404).send()
}
})
Here is my HTML + JS code (I know I don't need to have a function for this and can just use action="/users/login", but I want to use javascript to handle errors with the login):
<h1>Welcome</h1>
<form id="loginform" action="/users/login" method="POST">
<input type="text" name="email" id="email" placeholder="email">
<input type="password" name="password" id="password" placeholder="password">
<input type="submit">
</form>
<script>
const loginForm = document.querySelector('#loginform');
loginForm.addEventListener('submit', (e)=> {
e.preventDefault()
fetch('/users/login', { method: 'POST', body: new FormData(loginForm)} )
})
</script>