放置jwt.sign代码时出现JWT错误

时间:2018-02-21 11:21:52

标签: node.js authentication jwt

我正致力于创建身份验证系统,并试图找出如何使用JWT。我使用Node,express,passport和MYSQL。我尝试创建" var令牌"在db.sync()方法之后,但只会抛出错误,但如果我放入" var标记" db.sync()之前为什么会这样?我应该这样做吗?提前致谢!

var jwt = require('jsonwebtoken');

var config = require('../config'),
    db = require('../services/database'),
    User = require('../models/user'),
    Organisation = require('../models/organisation'),
    Event = require('../models/event');

// The authentication controller.
var AuthController = {};

// Register a user.
AuthController.signUp = function(req, res) {
    if(!req.body.username || !req.body.password || !req.body.email) {
        res.json({ message: 'Please provide a username and a password.' });
    } else {
      var token = jwt.sign({ username: req.body.username }, config.keys.secret, { expiresIn: '30m' });  
        db.sync().then(function() {

            var newUser = {
                username: req.body.username,
                password: req.body.password,
                email: req.body.email,
                temporarytoken: token
            };
            console.log(newUser.temporarytoken);
            return User.create(newUser).then(function() {
                res.status(201).json({ message: 'Account created!' });
            });
        }).catch(function(error) {
            res.status(403).json({ message: 'Username already exists!' });
        });
    }
}

1 个答案:

答案 0 :(得分:0)

您的错误消息是什么?

另外,如果您执行此代码,是否看到错误?

        db.sync().then(function() {
            var token = jwt.sign({ username: req.body.username }, config.keys.secret, { expiresIn: '30m' }); 

            var newUser = {
                username: req.body.username,
                password: req.body.password,
                email: req.body.email,
                temporarytoken: token
            };
            console.log(newUser.temporarytoken);
            return User.create(newUser).then(function() {
                res.status(201).json({ message: 'Account created!' });
            });

P.S。为什么要将令牌保存到数据库?您应该将jwt发送到客户端,客户端将其保存到本地存储或cookie。这就是jwt的重点。