首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法在nodejs后台获取令牌

无法在nodejs后台获取令牌
EN

Stack Overflow用户
提问于 2021-07-28 09:03:37
回答 1查看 52关注 0票数 0

我过去常常使用以下代码来获取我的登录令牌:

代码语言:javascript
复制
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"创建一个新的节点项目,但是现在当我尝试登录我的后端并得到没有出现的令牌时,我得到了这个错误消息

错误消息:

代码语言:javascript
复制
(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.

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

EN

回答 1

Stack Overflow用户

发布于 2021-07-29 06:33:57

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

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

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

代码语言:javascript
复制
require('dotenv').config();

const authSecret = process.env.authSecret;

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68553218

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档