login.js 和我的 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 和我的 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); } });
登录.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>
我检查了 html ID,检查了路由路径,更改了路由路径,但似乎没有任何效果。我收到 POST 400(错误请求)@login.js:10,这是获取。它确实正确地输出了我的用户名和密码。
P粉5433443812023-09-17 18:29:36
另一种方法是...
<button id="login-btn" type="submit" class="btn btn-secondary btn-sm" onclick="loginFormHandler()"> 提交 </button>
还要移除
//e.preventDefault();