【发布时间】:2021-09-09 16:10:47
【问题描述】:
我正在使用redis npm 包,每当我尝试连接到它时,它都会说host 和port 未定义。我打印出我的process.env 对象,我可以看到host 和port 设置了值。只有当我将值传递给我的 Redis 模型类的构造函数时,它才会变得未定义。有什么想法吗?
index.js
require('dotenv').config()
function startRedis() {
const redisInstance = new Redis(
process.env.REDIS_HOST,
process.env.REDIS_PORT
);
redisInstance.init();
}
class Redis {
constructor(redishost, redisport) {
this.redishost = redishost;
this.redisport = redisport;
}
async init() {
try {
this.redisClient = redis.createClient({
port: this.redisport,
host: this.redishost
});
console.log("port: ", this.port)
console.log("host: ", this.host)
} catch(error) {
console.log(`Error creating client due to: ${error}`)
}
}
.env
REDIS_HOST="value here"
REDIS_PORT="port value here"
package.json
{
"name": "app",
"version": "0.0.1",
"dependencies": {
"redis": "^3.0.2",
"dotenv": "^10.0.0"
},
"engines": {
"node": ">=10.0.0"
},
"main": "index.js",
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"devDependencies": {
"redis": "^3.0.2",
"dotenv": "^10.0.0"
}
}
Update 1:添加了我的 package.json
【问题讨论】:
-
你在阅读你的 .env 时喜欢使用
dotenv库吗?process.env.REDIS_HOST有价值吗?您尝试记录它吗? -
是的,我正在使用 dotenv 包。 @HellCatVN
-
是的,当我记录有值时。当构造函数尝试创建时,值是未定义的。
标签: javascript node.js npm server redis