得到错误:致命错误:未定义jwtPrivateKey。

时间:2019-02-07 08:25:21

标签: node.js

关于json网络令牌私钥,我仍然有一些异常错误。它说它没有定义,但是我想我已经放了json web令牌私钥并且仍然抛出错误。我不确定问题出在哪里,可能是用户模块或身份验证模块或配置中的问题。请查看下面的代码,任何帮助将不胜感激。

    //default.json
        {
        "jwtPrivateKey": "",
        "db": "mongodb://localhost/vidly"
        }

        // test.json
        {
        "jwtPrivateKey": "1234",
        "db": "mongodb://localhost/vidly_tests"
        }
        // config.js
        const config = require('config');

        module.exports = function() {
        if (!config.get('jwtPrivateKey')) {
        throw new Error('FATAL ERROR: jwtPrivateKey is not defined.');
        }
        }
        // users.js
        const auth = require('../middleware/auth');
        const jwt = require('jsonwebtoken');
        const config = require('config');
        const bcrypt = require('bcrypt');
        const _ = require('lodash');
        const {User, validate} = require('../models/user');
        const mongoose = require('mongoose');
        const express = require('express');
        const router = express.Router();

        router.get('/me', auth, async (req, res) => {
        const user = await User.findById(req.user._id).select('-password');
        res.send(user);
        });

        router.post('/', async (req, res) => {
        const { error } = validate(req.body); 
        if (error) return res.status(400).send(error.details[0].message);

        let user = await User.findOne({ email: req.body.email });
        if (user) return res.status(400).send('User already registered.');

        user = new User(_.pick(req.body, ['name', 'email', 'password']));
        const salt = await bcrypt.genSalt(10);
        user.password = await bcrypt.hash(user.password, salt);
        await user.save();

        const token = user.generateAuthToken();
        res.header('x-auth-token', token).send(.pick(user, ['id', 'name', 'email']));
        });

        module.exports = router;

// auth.js

const Joi = require('joi');
const bcrypt = require('bcrypt');
const _ = require('lodash');
const {User} = require('../models/user');
const mongoose = require('mongoose');
const express = require('express');
const router = express.Router();

router.post('/', async (req, res) => {
  const { error } = validate(req.body); 
  if (error) return res.status(400).send(error.details[0].message);

  let user = await User.findOne({ email: req.body.email });
  if (!user) return res.status(400).send('Invalid email or password.');

  const validPassword = await bcrypt.compare(req.body.password, user.password);
  if (!validPassword) return res.status(400).send('Invalid email or password.');

  const token = user.generateAuthToken();
  res.send(token);
});

function validate(req) {
  const schema = {
    email: Joi.string().min(5).max(255).required().email(),
    password: Joi.string().min(5).max(255).required()
  };

  return Joi.validate(req, schema);
}

module.exports = router; 


        // db.js
        const winston = require('winston');
        const mongoose = require('mongoose');
        const config = require('config');

        module.exports = function() {
        const db = config.get('db');
        mongoose.connect(db)
        .then(() => winston.info(Connected to ${db}...));
        }
        // logging.js
        const winston = require('winston');
        // require('winston-mongodb');
        require('express-async-errors');

        module.exports = function() {
        winston.handleExceptions(
        new winston.transports.Console({ colorize: true, prettyPrint: true }),
        new winston.transports.File({ filename: 'uncaughtExceptions.log' }));


        process.on('unhandledRejection', (ex) => {
        throw ex;
        });


        winston.add(winston.transports.File, { filename: 'logfile.log' });
        // winston.add(winston.transports.MongoDB, { 
        // db: 'mongodb://localhost/vidly',
        // level: 'info'
        // }); 

        }
        // index.js
        const winston = require('winston');
        const express = require('express');
        const app = express();

        require('./startup/logging')();
        require('./startup/routes')(app);
        require('./startup/db')();
        require('./startup/config')();
        require('./startup/validation')();

        const port = process.env.PORT || 3000;
        app.listen(port, () => winston.info(Listening on port ${port}...));

        // user.test.js
        const {User} = require('../../../models/user');
        const jwt = require('jsonwebtoken');
        const config = require('config');
        const mongoose = require('mongoose');

        describe('user.generateAuthToken', () => {
        it('should return a valid JWT', () => {
        const payload = { 
        _id: new mongoose.Types.ObjectId().toHexString(), 
        isAdmin: true 
        };
        const user = new User(payload);
        const token = user.generateAuthToken();
        const decoded = jwt.verify(token, config.get('jwtPrivateKey'));
        expect(decoded).toMatchObject(payload);
        });
        });

        // package.json

        "scripts": {
        "test": "jest --watchAll --verbose"
        },

3 个答案:

答案 0 :(得分:1)

尝试使用config.get而不是config.has()

 module.exports = function() {
    if (!config.has('jwtPrivateKey')) {
    throw new Error('FATAL ERROR: jwtPrivateKey is not defined.');
 }

答案 1 :(得分:0)

我认为set与Visual Studio Code终端不兼容。我在Windows CMD中执行该命令时也遇到了同样的问题。

答案 2 :(得分:0)

您的配置文件结构错误。如果您检查https://www.npmjs.com/package/config

这是文件的结构:

{
  "Customer": {
    "dbConfig": {
      "host": "prod-db-server"
    },
    "credit": {
      "initialDays": 30
    }
  }
}

该页面还提供了以下信息:

config.get()将为未定义的键引发异常,以帮助捕获错别字和缺失值。使用config.has()测试是否定义了配置值。