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>
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):
TL;DR Use action
instead of fetch()
. If you need help with the error handling part, post a new question about it.
Using action
for form submission and JavaScript for error handling are not mutually exclusive. The problem here is that fetch()
makes an AJAX request which returns the response as a value directly in the current page. It will not automatically redirect according to the response code. You can add some additional logic to do this, but why make this more complicated than necessary.
Instead add an action
attribute to your <form>
:
<form name="login" id="loginform" action="/users/login/" method="POST">
Then write JavaScript to do your error handling. Only call preventDefault()
when there is an error to prevent the form submission. But allow normal submission when there is no errors.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加