【问题标题】:Node JS : How to retrive data from frontend after a res.json(data) in backend?Node JS:如何在后端的 res.json(data) 之后从前端检索数据?
【发布时间】:2021-09-13 18:11:15
【问题描述】:

我的后端向我的前端发送 res.staus(200).json({somedata)},但我无法在前端检索数据。

我的后台:

exports.login = (req, res, next) => {
  //===== Check if user exists in DB ======
  const { user_email, user_password: clearPassword } = req.body;
  let sql = `SELECT user_password, user_id FROM users WHERE user_email=?`;
  db.query(sql, [user_email], async (err, results) => {
    console.log(results);
    console.log(req.body);
    if (err) {
      return res.status(404).json({ err });
    }

    // ===== Verify password with hash in DB ======
    const { user_password: hashedPassword, user_id } = results[0];
    try {
      const match = await bcrypt.compare(clearPassword, hashedPassword);
      if (match) {
        console.log("match ... user_id : ", user_id);

        // If match, generate JWT token
        res.status(200).json({
          test: 'iyu',
          user_id: user_id,
          token: jwt.sign({ userId: user_id }, "TOOOKEN", {
            expiresIn: "24h",
          }),
        });
      } else {
        console.log("not match");
      }
    } catch (err) {
      return res.status(400).json({ err: "une erreur" });
    }
  });
};

前端:

 const login = async (e) => {
    e.preventDefault();
    await POST(ENDPOINTS.USER_LOGIN, userLogin);
    // await GET(ENDPOINTS.USER_LOGIN)
    fetch("http://localhost:4200/api/auth/login")
      .then((response) => response.json())
      .then((data) => {
        console.log(data);
      });
  };

此登录功能将数据发送到我的后端,然后后端使用第一个 POST 请求检查数据库中是否存在用户。如果是,后端以 json 格式发送一些我不想放在用户本地存储中的数据,所以在 POST 请求之后,我使用 GET 方法执行另一个请求以检索从后面发送的 json 数据,但是我遇到了 404 错误。

我怎样才能让我的数据被后台发过来?

【问题讨论】:

  • 您没有在 GET 请求中发送任何参数。后端应该如何知道您要检索哪个用户?此外,您的后端函数期望在 req.body 中找到用户的凭据,但获取请求中没有正文。

标签: node.js reactjs


【解决方案1】:

似乎问题出在 SQL 语句上,在 if 语句下你可以像这样打印错误:

if(err) {
    console.log(err);
}

请告诉我结果

【讨论】:

    猜你喜欢
    • 2021-11-28
    • 1970-01-01
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-05-17
    • 2020-12-22
    • 2021-07-01
    • 1970-01-01
    相关资源
    最近更新 更多