错误:配置验证错误:子级“ JWT_SECRET”失败,因为[需要“ JWT_SECRET”]

时间:2019-05-08 17:45:29

标签: javascript node.js mongodb express mongoose

我目前正在建立基于NODE的项目。我为该项目设计了一个api。当我运行服务器时,api工作正常。因此,在下一步中,我为api编写了一个测试用例。它给了我一个意想不到的结果。我的代码掉到了我的config.js文件中。经过一些调试后,我发现它无法接受来自process.ENV的输入。但是,我不明白为什么不能这样做。我在根文件夹中定义了一个.env文件。我在这里共享我的folder structureconfig.jstest.js.env文件。请检查一下,让我知道我在这里错过了哪些事情。

文件夹结构

project
│   README.md
│   config
|   |___config.js
│
└───server
│   │   
│   │___helpers
│   │
│   └───registration
│       │______ user
|                 |_____ user.route.js 
│                 |_____ user.model.js
|                 |_____ user.controller.js
│                 |_____ user.test.js
│   
|───.env
|___ package.json
|___ index.js
|___ index.route.js

Config.js

const Joi = require('joi');

// require and configure dotenv, will load vars in .env in PROCESS.ENV
require('dotenv').config();

console.log(process.env.PORT);
// define validation for all the env vars
const envVarsSchema = Joi.object({
  NODE_ENV: Joi.string()
    .allow(['development', 'production', 'test', 'provision'])
    .default('development'),
  PORT: Joi.number()
    .default(4040),
  MONGOOSE_DEBUG: Joi.boolean()
    .when('NODE_ENV', {
      is: Joi.string().equal('development'),
      then: Joi.boolean().default(true),
      otherwise: Joi.boolean().default(false)
    }),
  JWT_SECRET: Joi.string().required()
    .description('JWT Secret required to sign'),
  MONGO_HOST: Joi.string().required()
    .description('Mongo DB host url'),
  MONGO_PORT: Joi.number()
    .default(27017)
}).unknown()
  .required();

const { error, value: envVars } = Joi.validate(process.env, envVarsSchema);
if (error) {
  throw new Error(`Config validation error: ${error.message}`);
}

const config = {
  env: envVars.NODE_ENV,
  port: envVars.PORT,
  mongooseDebug: envVars.MONGOOSE_DEBUG,
  jwtSecret: envVars.JWT_SECRET,
  mongo: {
    host: envVars.MONGO_HOST,
    port: envVars.MONGO_PORT
  }
};

module.exports = config;

user.test.js

const mongoose = require('mongoose');
const request = require('supertest-as-promised');
const httpStatus = require('http-status');
const chai = require('chai'); // eslint-disable-line import/newline-after-import
const expect = chai.expect;
const app = require('../../../index');

chai.config.includeStack = true;

/**
 * root level hooks
 */
after((done) => {
  mongoose.models = {};
  mongoose.modelSchemas = {};
  mongoose.connection.close();
  done();
});

describe('## User APIs', () => {
  let user = {
    name: 'KK123',
    gender: 'male',
    skillArea: 'nodeJs',
    email: 'a@a.com',
    mobileNumber: '1234567890',
    password: '123456'
  };

  describe('# POST /api/v1/register/user', () => {
    it('should create a new user', (done) => {
      request(app)
        .post('/api/v1/register/user')
        .send(user)
        .expect(httpStatus.OK)
        .then((res) => {
          expect(res.body.name).to.equal(user.name);
          expect(res.body.gender).to.equal(user.gender);
          expect(res.body.skillArea).to.equal(user.skillArea);
          expect(res.body.email).to.equal(user.email);
          expect(res.body.mobileNumber).to.equal(user.mobileNumber);
          expect(res.body.password).to.equal(user.password);
          user = res.body;
          done();
        })
        .catch(done);
    });
  });
});

.env

NODE_ENV=development
PORT= 4040
JWT_SECRET = "Testpurposeonly"
MONGO_HOST = mongodb://localhost/user
MONGO_PORT = 27017

1 个答案:

答案 0 :(得分:0)

我通过导出const a: T = { a: false, b: true } delete a.b 解决了该问题。我使用的命令是

JWT_SECRET