为什么我的路由路径有一个错误的请求

问题描述 投票:0回答:1

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);
  }
});

登录.车把

 <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,这是获取。它确实正确地输出了我的用户名和密码。

javascript html handlebars.js
1个回答
0
投票

做同样事情的另一种方法可以是...... 更改按钮类型以提交并在按钮的“onClick”上添加您的功能。

<button id="login-btn" type="button" class="btn btn-secondary btn-sm" 
onclick="loginFormHandler()">
    Submit
  </button>

并删除

//e.preventDefault();
© www.soinside.com 2019 - 2024. All rights reserved.