【问题标题】:Unable to get a token on a nodejs backend无法在 nodejs 后端获取令牌
【发布时间】:2021-10-03 18:30:20
【问题描述】:

我曾经使用此代码获取我的登录令牌:

1const { authSecret } = require('../.env');
2const jwt = require('jwt-simple');
3const bcrypt = require('bcrypt-nodejs');
4
5module.exports = app => {
6  const signin = async (req, res) => {
7    if (!req.body.email || !req.body.password) {
8     return res.status(400).send('Enter user and password ');
9    };
10
11    const user = await app.db('users')
12      .where({ email: req.body.email })
13      .first()
14
15    if (!user) return res.status(400).send('User not found!');
16
17    const isMatch = bcrypt.compareSync(req.body.password, user.password);
18    if (!isMatch) return res.status(401).send('Invalid email/password!');
19
20    const now =  Math.floor(Date.now() / 1000);
21
22    const payload = {
23      id: user.id,
24      name: user.name,
25      email: user.email,
26      age: user.age,
27      city: user.city,
28      iat: now,
29      exp: now + (60 * 60 * 24 * 7)
30    };
31
32    res.json({
33      ...payload,
34      token: jwt.encode(payload, authSecret)
35    })
36  };
37
38  const validadeToken = async (req, res) => {
39    const userData = req.body || null;
40      try {
41        if (userData) {
42            const token = jwt.decode(userData.token, authSecret)
43            if(new Date(token.exp * 1000) > new Date()) {
44              req.send(true)
45            }
46        }
47      } catch (e) {
48        console.log('Inspired token');
49      };
50
51      res.send(false);
52  };
53
54  return { signin, validadeToken };
55}
56

但昨天我尝试使用"bcrypt-nodejs": "^0.0.3""jwt-simple": "^0.5.6" 创建一个新节点项目,但现在当我尝试登录后端并获取未出现的令牌时收到此错误消息

错误信息:

(node:13188) UnhandledPromiseRejectionWarning: Error: Require key
    at Object.jwt_encode [as encode] (F:\react_native\Expo\base\track-server\node_modules\jwt-simple\lib\jwt.js:123:11)
    at signin (F:\react_native\Expo\base\track-server\api\auth.js:34:18)
    at processTicksAndRejections (internal/process/task_queues.js:97:5)
(node:13188) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:13188) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

有谁知道我应该怎么做才能得到这个登录令牌?

【问题讨论】:

  • 我不会使用包bcrypt-nodejs,因为该包很久以前就已经贬值了。而是使用位于npmjs.com/package/bcrypt的包bcrypt
  • 我在这个项目上也有 bcrypt 库,但我不能只在第 3 行将 bcypt-nodejs 库更改为 bcrypt,可以吗?

标签: node.js jwt backend bcrypt payload


【解决方案1】:

看起来您的authSecret 变量是undefined,因此当您在第34 行的jwt.encode(payload, authSecret) 调用期间尝试将其用作键时会导致Error: Require key 错误。

由于您似乎已经有一个.env 文件,我建议在这里使用dovenv 模块https://www.npmjs.com/package/dotenv

因此假设您的.env 文件位于项目的根目录中。将您的解构导入 const { authSecret } = require('../.env'); 替换为

require('dotenv').config();

const authSecret = process.env.authSecret;

(显然用.env 文件中定义的环境变量替换authSecret)。同样仅供参考,将环境变量设为大写并用下划线分隔是惯例。例如AUTH_SECRET

【讨论】:

  • 谢谢,但我也有一个用户 API,我在其中注册的用户也显示此错误,但用户正在注册。您可以在尝试登录之前和注册之后查看我的 GITHUB github.com/GlaudistonNeto/blogRnV4 存储库。我没有在那里使用 env 文件,因为我不需要它。如果你也可以帮助我在那里尝试一些东西,我会很高兴。感谢您的帮助
  • @GNeto 抱歉,我不确定我是否理解这个问题,你确定这是同一个错误吗?我查看了您的 github 存储库,但没有看到您使用 jwt-simple 模块的任何地方,当您调用 jwt.decode 时没有给出错误的密钥时,它就是该模块。
  • 没错。我想说的是,在我尝试使用 jwt-simple 之前,在我的 Github 中有这个存储库,在我尝试之后,我得到了错误结束,我试图在这里获得一些帮助。我只是想向您展示我正在尝试注册和登录用户的完整存储库。
猜你喜欢
  • 2016-01-19
  • 2022-07-08
  • 2015-02-11
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 2017-10-02
  • 2018-01-19
  • 2012-05-27
相关资源
最近更新 更多