login.js and 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 and 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 ID, checked the routing path, changed the routing path, but nothing seems to work. I'm getting POST 400 (Bad Request) @login.js:10 and this is getting. It does output my username and password correctly.
Another way is...
Also removed