无法在 nodejs 后端获取令牌

问题描述

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

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.

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

解决方法

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

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

因此假设您的 .env 文件位于项目的根目录中。用

替换你解构的导入const { authSecret } = require('../.env');
require('dotenv').config();

const authSecret = process.env.authSecret;

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