我正在尝试在用户创建帐户时生成令牌,但是我似乎得到了一个空集?有什么事吗语法有什么问题吗?
这是控制器文件:
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);
}
},
这是助手实用程序文件: 这是我具有生成令牌功能的文件。
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;
答案 0 :(得分:1)
我相信您的ID必须是一个对象。 从docs:
var token = jwt.sign({ foo: 'bar' }, 'shhhhh');
尝试
var token = jwt.sign({id: id}, process.env.SECRET, {expiresIn: '7d'});