gpt4 book ai didi

javascript - 我如何生成 token ?

转载 作者:行者123 更新时间:2023-12-03 00:32:27 27 4
gpt4 key购买 nike

我试图在用户创建帐户时生成一个 token ,但我似乎得到一个空集?可能出什么问题了?语法有问题吗?

这是 Controller 文件:

import moment from 'moment';
import uuidv4 from 'uuidv4';
import db from '../db/index';
import Helper from '../middleware/helper';


const users = {

async createAccount(req, res) {
if (!req.body.email || !req.body.password) {
return res.status(400).send({ 'message': 'Some values are missing' });
}
if (!Helper.isValidEmail(req.body.email)) {
return res.status(400).send({ 'message': 'Please enter a valid email address' });
}
const hashPassword = Helper.hashPassword(req.body.password);

const createQuery = `INSERT INTO
users (id, firstName, lastName, otherNames, email, phoneNumber, userName, registered, isAdmin, password)
VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
returning *`;
const values = [
uuidv4(),
req.body.firstName,
req.body.lastName,
req.body.otherNames,
req.body.email,
req.body.phoneNumber,
req.body.userName,
moment(new Date()),
req.body.isAdmin,
hashPassword,
];

try {
const { rows } = await db.query(createQuery, values);
const token = Helper.generateToken(rows[0].id);
return res.status(201).send({ token });
} catch (error) {
if (error.routine === '_bt_check_unique') {
return res.status(400).send({ 'message': 'User with that EMAIL already exist' });
}
return res.status(400).send(error);
}
},

这是 Helper utils 文件:这是我具有生成 token 功能的文件。

import bcrypt from 'bcrypt';
import jwt from 'jsonwebtoken';

const Helper = {

generateToken(id) {
const token = jwt.sign(id, process.env.SECRET, { expiresIn: '7d' });
return token;
},
};

export default Helper;

最佳答案

我相信你的 id 需要是一个对象。来自 docs :

var token = jwt.sign({ foo: 'bar' }, 'shhhhh');

尝试

var token = jwt.sign({id: id}, process.env.SECRET, {expiresIn: '7d'});

关于javascript - 我如何生成 token ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53797409/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com