login.js with my fetch
const loginFormHandler = async (e) => {
e.preventDefault();
const username = document.getElementById('inputUsername').value.trim();
const userPassword = document.getElementById('inputPassword').value.trim();
if (username && userPassword) {
console.log(username);
console.log(userPassword);
const res = await fetch('/api/users/login', {
method: 'POST',
body: JSON.stringify({ username, userPassword }),
headers: { 'Content-Type': 'application/json' },
})
if (res.ok) {
document.location.replace('/profile');
} else {
console.log(res.statusText);
}
}
};
userRoutes.js with my POST
router.post('/login', async (req, res) => {
try {
const userData = await User.findOne({ where: { username: req.body.username } });
console.log(userData);
if (!userData) {
res
.status(400)
.json({ message: 'Incorrect username or password, please try again' });
return;
}
const validPassword = await userData.checkPassword(req.body.password);
console.log(validPassword);
if (!validPassword) {
res
.status(400)
.json({ message: 'Incorrect username or password, please try again' });
return;
}
req.session.save(() => {
req.session.user_id = userData.id;
req.session.logged_in = true;
res.json({ user: userData, message: 'You are now logged in!' });
});
} catch (err) {
res.status(400).json(err);
}
});
login.handlebars
<form class="loginFormHandler">
<label for="inputUsername">Username</label>
<input type="form-input" class="form-control" id="inputUsername" />
<label for="inputPassword">Password</label>
<input type="password" class="form-control" id="inputPassword" />
<small id="passwordHelp" class="form-text text-muted">Never share
your password.</small>
<button id="login-btn" type="submit" class="btn btn-secondary btn-sm">Submit</button>
</p>
</form>
I checked the html IDs, checked the route path, changed the route path and nothing seems to be working. I get a POST 400 (bad request) @login.js:10 which is the fetch. It does console out my username and password correctly.