简体   繁体   English

.env 文件未定义使用 require('dotenv').config();

[英].env file undefined using require('dotenv').config();

Having trouble with getting dotenv to pick up my.env file让 dotenv 获取 my.env 文件时遇到问题

Here is my file structure:这是我的文件结构:

├── app.js
├── node_modules
│   └── ...
├── package.json
├── routes
│   └── index.js
└── start.js
│   
└── .env 

And here is my start.js:这是我的 start.js:

require('dotenv').config();
console.log(process.env.MONGO_URI);
const mongoose = require('mongoose');


mongoose.connect(process.env.DATABASE, { useMongoClient: true });
mongoose.Promise = global.Promise;
mongoose.connection
  .on('connected', () => {
    console.log(`Mongoose connection open on ${process.env.DATABASE}`);
  })
  .on('error', (err) => {
    console.log(`Connection error: ${err.message}`);
  });

inside my.env is as follows: my.env 里面如下:

mongodb+srv://username:password@livewelldb-aqoul.mongodb.net/test?retryWrites=true&w=majority

Unfortunately, when running my node.js app I get the following error:不幸的是,在运行我的 node.js 应用程序时,我收到以下错误:

C:\Users\user\Desktop\project\node_modules\mongoose\lib\connection.js:520
    throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
    ^
MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.

this is happening because dotenv does not seem to be able to find my.env file for some reason.发生这种情况是因为 dotenv 由于某种原因似乎无法找到 my.env 文件。 when I run console.log(process.env.MONGO_URI);当我运行console.log(process.env.MONGO_URI); I get undefined.我不确定。

No idea why.不知道为什么。 Most people with this issue have one of the following problems:大多数有此问题的人都有以下问题之一:

  • they don't run their program from the root directory他们不从根目录运行他们的程序
  • their.env is not in their root directory their.env 不在他们的根目录中
  • their.env is named incorrectly, eg "config.env"他们的.env 命名不正确,例如“config.env”
  • their.env is formatted in something other than UTF-8 their.env 的格式不是 UTF-8

I do not have any of these problems.我没有任何这些问题。 I'm not sure what could be causing it.我不确定是什么原因造成的。

Any ideas?有任何想法吗?

specify your.dotenv file name in the package upon loading the app在加载应用程序时在 package 中指定 your.dotenv 文件名

require('dotenv').config({path: './.env'})

Please check your .dotenv file name.请检查您的.dotenv文件名。

require('dotenv').config({path:'relative/path/to/your/.env'})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM