javascript - 通过express处理jwt token 返回错误 "const token = req.cookies.auth; [0] ^ [0] [0] ReferenceError: req is not defined"

标签 javascript node.js express jwt

我正在尝试完成 jwt 登录我正在尝试在登录中创建 jwt token 。然后我尝试在我的用户问题路由中使用它。

我正在使用 react 前端。

这是正确的方法吗?

我目前遇到错误

const token = req.cookies.auth;
[0]               ^
[0]
[0] ReferenceError: req is not defined

下面是我的路由登录代码,一旦我的sql服务器返回电子邮件和密码的值存在,它就会分配 token 。用户问题尝试使用此 jwt。我还包括了如何在函数中验证 token

验证用户

app.get("/user-questions", verifyToken, function(req, res) {
  app.use(function(req, res, next) {
    // decode token
    if (token) {
      jwt.verify(token, "secret", function(err, token_data) {
        if (err) {
          console.info("token did not work");
          return res.status(403).send("Error");
        } else {
          req.user_data = token_data;
          sql.connect(config, function(err) {
            if (err) console.log(err);

            // create Request object
            var request = new sql.Request();

            // query to the database and get the records
            request.execute("dbo.ViewQuestions", function(err, recordset) {
              if (err) console.log(err);

              // send records as a response

              res.json(recordset);
              next();
            });
          });
        }
      });
    } else {
      console.info("no token");
      console.log("no token");
      return res.status(403).send("No token");
    }
  });
});

登录路径

app.post("/login", async (req, response) => {
  try {
    await sql.connect(config);

    var request = new sql.Request();
    var Email = req.body.email;
    var Password = req.body.password;

    console.log({ Email, Password });

    request.input("Email", sql.VarChar, Email);
    request.input("Password", sql.VarChar, Password);

    var queryString =
      "SELECT * FROM TestLogin WHERE email = @Email AND password = @Password";

    //"SELECT * FROM RegisteredUsers WHERE email = @Email AND Password = HASHBYTES('SHA2_512', @Password + 'skrrt')";

    const result = await request.query(queryString);

    if (result.recordsets[0].length > 0) {
      console.info("/login: login successful..");
      console.log(req.body);

      token = jwt.sign(
        { Email },
        "secretkey",
        { expiresIn: "30s" },
        (err, token) => {
          res.json({
            token
          });
          res.cookie("auth", token);
          res.send("ok");
        }
      );
    } else {
      console.info("/login: bad creds");
      response.status(400).send("Incorrect email and/or Password!");
    }
  } catch (err) {
    console.log("Err: ", err);
    response.status(500).send("Check api console.log for the error");
  }
});

验证用户


// Verify Token
function verifyToken(req, res, next) {
  // Get auth header value
  const bearerHeader = req.headers["authorization"];
  // Check if bearer is undefined
  if (typeof bearerHeader !== "undefined") {
    // Split at the space
    const bearer = bearerHeader.split(" ");
    // Get token from array
    const bearerToken = bearer[1];
    // Set the token
    req.token = bearerToken;
    // Next middleware
    next();
  } else {
    // Forbidden
    res.sendStatus(403);
  }
}

请告知这在理论上是否可行。如果没有,请告知如何解决。

编辑:

错误已解决,但现在我的 jwt token 不起作用。当登录时,我手动路由到用户问题,它不会加载组件,并且在控制台中显示 403 不可用(这是在 jwt token 不起作用时在代码中设置的)。

更新:

我该如何包含

 ['authorization'] = 'Bearer ' + token;

进入


 handleSubmit(e) {
    e.preventDefault();
    if (this.state.email.length < 8 || this.state.password.length < 8) {
      alert(`please enter the form correctly `);
    } else {
      const data = { email: this.state.email, password: this.state.password };

      fetch("/login", {
        method: "POST", // or 'PUT'
        headers: {
          Accept: "application/json, text/plain, */*",
          "Content-Type": "application/json",

        },
        body: JSON.stringify(data)
      })
        // .then(response => response.json())
        .then(data => {
          console.log("Success:", data);


        })

        .catch(error => {
          console.error("Error:", error);
        });
    }
  }

最佳答案

您的代码有几个错误:

  • 在您的 /login route :
    • 您正在尝试在发送响应后设置“auth”cookie
    • 您尝试发送响应两次,一次通过 res.json,一次通过 res.send
    • 您正在分配给不再存在的 token 变量 (token = jwt.sign(...))
  • 在您的 verifyToken 方法中:
    • 此方法仅验证请求是否具有 token 集,而不是验证或解码它。我会考虑将您的 jwt.verify() 调用移至此方法。
  • 在您的 /user-questions route :
    • 您正在 app.get 内部调用 app.use,而这两个方法都打算在根级别调用。删除您的 app.use 调用。
    • 您需要从请求中获取 token ,例如。 const { token } = req;
    • 您正在通过 res.json() 发送响应,但之后仍调用 next()。来自 Express docs :

      If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function.

<小时/>

这就是我进行这些更改的方式:

  • /login 路线:
app.post("/login", async (req, response) => {
  try {
    await sql.connect(config);

    var request = new sql.Request();
    var Email = req.body.email;
    var Password = req.body.password;

    console.log({ Email, Password });

    request.input("Email", sql.VarChar, Email);
    request.input("Password", sql.VarChar, Password);

    var queryString =
      "SELECT * FROM TestLogin WHERE email = @Email AND password = @Password";

    //"SELECT * FROM RegisteredUsers WHERE email = @Email AND Password = HASHBYTES('SHA2_512', @Password + 'skrrt')";

    const result = await request.query(queryString);

    if (result.recordsets[0].length > 0) {
      console.info("/login: login successful..");
      console.log(req.body);

      jwt.sign(
        { Email },
        "secretkey",
        { expiresIn: "30s" },
        (err, token) => res.cookie('auth', token).json({ token })
      );
    } else {
      console.info("/login: bad creds");
      response.status(400).send("Incorrect email and/or Password!");
    }
  } catch (err) {
    console.log("Err: ", err);
    response.status(500).send("Check api console.log for the error");
  }
});
  • verifyToken 方法:
// Verify Token
function verifyToken(req, res, next) {
  // Get auth header value
  const bearerHeader = req.headers["authorization"];
  // Check if bearer is undefined
  if (typeof bearerHeader !== "undefined") {
    // Split at the space
    const bearer = bearerHeader.split(" ");
    // Get token from array
    const bearerToken = bearer[1];

    // verify the token and store it
    jwt.verify(bearerToken, "secret", function(err, decodedToken) {
      if (err) {
        console.info("token did not work");
        return res.status(403).send("Error");
      }

      // Set the token
      req.token = bearerToken;
      req.decodedToken = decodedToken;

      next();
    });
  } else {
    // Forbidden
    res.sendStatus(403);
  }
}
  • /用户问题路线:
app.get("/user-questions", verifyToken, function(req, res) {
  // if a request has made it to this point, then we know they have a valid token
  // and that token is available through either req.token (encoded)
  // or req.decodedToken

  sql.connect(config, function(err) {
    if (err) console.log(err);

    // create Request object
    var request = new sql.Request();

    // query to the database and get the records
    request.execute("dbo.ViewQuestions", function(err, recordset) {
      if (err) console.log(err);

      // send records as a response

      res.json(recordset);
    });
  });
});

关于javascript - 通过express处理jwt token 返回错误 "const token = req.cookies.auth; [0] ^ [0] [0] ReferenceError: req is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59752706/

相关文章:

javascript - 转换方程

javascript - window.location.href 不适用于 IE

javascript - 如何在在线服务器上存储鼠标坐标?

node.js - 如何在 docker 中使用 certbot 正确安装 ssl 证书?

css - 是否有可以使用 Express 4.0 在 Node 网络服务器上编译 LESS CSS 的中间件?

javascript - SAPUI5:如何在运行时创建XMLView及其 Controller ?

javascript - Node js,函数不等待响应

javascript - Angular 参数和 Express 命中了错误的请求 URL

javascript - 同步 dnode 和 Express 身份验证 - 如何?

javascript - JQuery 验证 - 文本输入所需的单选按钮