【问题标题】:Error: Config validation error: child "JWT_SECRET" fails because ["JWT_SECRET" is required]错误:配置验证错误:子“JWT_SECRET”失败,因为[需要“JWT_SECRET”]
【发布时间】:2019-05-12 22:11:14
【问题描述】:

我目前正在开发基于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

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    我通过导出JWT_SECRET 解决了这个问题。我使用的命令是

    export JWT_SECRET = mysecretkey

    【讨论】:

      猜你喜欢
      • 2019-03-05
      • 2020-12-27
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-02
      • 2020-03-15
      相关资源
      最近更新 更多