我的路由路徑出現錯誤請求的原因是什麼?
P粉218361972
P粉218361972 2023-09-16 21:36:52
0
1
599

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粉218361972
P粉218361972

全部回覆(1)
P粉543344381

另一種方法是...

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

還要移除

//e.preventDefault();
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板