20210914 - Fail to access environment variables from .env file
2021-09-14 00:00:00

之前在一个React的Demo中用api获取天气信息的时候用到过环境变量,大概就是三个步骤,第一:把REACT_APP_API_KEY的value保存在.env文件里;第二:通过process.env.REACT_APP_API_KEY获取和使用value;第三:把.env加到.gitignore里,避免被push到git repository。

这次的目标是连接Node.js后端和MongoDB。MongoDB的URL中的password需要保存为环境变量,我就完全按照上次总结的步骤行事,但是报错了。直接在URL中写入password的值和console(password)后发现这个error应该是没有获取到环境变量导致的。

Untitled

解决方法

第一步:添加dotenv依赖

1
2
3
4
5
6
7
npm install dotenv
"dependencies": {
"cors": "^2.8.5",
**"dotenv": "^10.0.0",**
"express": "^4.17.1",
"mongoose": "^6.0.5"
},

关于dotenv

Dotenv is a zero-dependency module that loads environment variables from a .env file into [process.env](<https://nodejs.org/docs/latest/api/process.html#process_process_env>). Storing configuration in the environment separate from code is based on The Twelve-Factor App methodology.

第二步:在index.js中引入

1
2
const dotenv = require('dotenv')
dotenv.config()

关于config

config will read your .env file, parse the contents, assign it to process.env, and return an Object with a parsed key containing the loaded content or an error key if it failed.

然后就和数据库连接成功了!

个人总结

大概.env里的环境变量在Node.js这边不能直接获取和使用,需要先添加dotenv依赖后才可。

参考

Connecting to MongoDB using Mongoose 🌳