【问题标题】:bcrypt.compare cannot set response headers in nextjsbcrypt.compare 无法在 nextjs 中设置响应标头
【发布时间】:2020-01-26 09:34:33
【问题描述】:

当我的代码进入 bcrypt.compare 时,我似乎无法获得正确的响应标头。一开始我以为是cors问题,但如果输入错误并显示“用户不存在”,我仍然会得到正确的响应。

这是我在 express 中的 api 服务器端代码

router.post("/api/signIn", (req, res) => {
  const { user, password } = req.body;
  const queryString = "SELECT * FROM users WHERE user_id = ?";
  db.query(queryString, [user])
    .then(result => {
      if (result.length > 0) {
        const hash = result[0].password;

        //here bcrypt.compare works server side or with cURL but won't set the response headers in the browser

        bcrypt
          .compare(password, hash)
          .then(same => {
            if (same === true) {
              console.log("correct password");
              res.status(200).json({
                code: 200,
                message: "correct password"
              });
            } else {
              res.status(401).json({
                code: 401,
                message: "incorrect password"
              });
            }
          })
          .catch(err => console.log(err));
      } else {

      //this one works though and i can get the response in the browser so it can't be a cors issue

        console.log("user does not exist");
        res.status(200).json({
          code: 401,
          message: "User does not exist"
        });
      }
    })
    .catch(err => {
      console.log("error" + err.message);
    });
});

这是我在 react 中使用的测试函数

  const signIn = () => {
    fetch("http://localhost:5000/api/signIn", {
      method: "POST",
      body: JSON.stringify({
        user: userName,
        password: password
      }),
      headers: {
        "Content-Type": "application/json"
      },
    })
      .then(res => res.json())
      .then(response => alert(response.code + response.message))
      .catch(err => alert(err));
  };

因此,如果我输入了错误的用户名,而该用户名不在数据库中,则会显示警报功能(code401User 不存在)但如果我输入了正确的用户 bcrypt.compare() 似乎不会为两者设置响应正确和不正确的密码,我会得到(TypeError:无法获取)。但是在 cURL 中测试 api 是可行的。

【问题讨论】:

  • 您能否检查浏览器的控制台以获取有关错误的更多详细信息,例如 CORS?
  • @SureshPrajapati 是这个吗?用户:sad 和密码:sad 存在于数据库中,因此它应该返回消息:“正确的密码” 请求 URL:localhost:5000/api/signIn 推荐人策略:no-referrer-when-downgrade 显示临时标题内容类型:应用程序/json DNT : 1 推荐人: localhost:3000/signin Sec-Fetch-Mode: cors 用户代理: Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Mobile Safari/ 537.36 {用户:“悲伤”,密码:“悲伤”}密码:“悲伤”用户:“悲伤”

标签: javascript express bcrypt next.js


【解决方案1】:

知道了,我忘了把 event.preventDefault() 放在 fetch 函数上。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    • 2021-07-06
    • 2016-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多