【问题标题】:redis port and host undefined even though env are set即使设置了 env,redis 端口和主机也未定义
【发布时间】:2021-09-09 16:10:47
【问题描述】:

我正在使用redis npm 包,每当我尝试连接到它时,它都会说hostport 未定义。我打印出我的process.env 对象,我可以看到hostport 设置了值。只有当我将值传递给我的 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


【解决方案1】:

我可以在这里看到process.env.REDIS_HOST 是否有价值。

你有新的班级名称错误

你的启动函数应该是这样的


function startRedis() {
    const redisInstance = new Redis(
        process.env.REDIS_HOST,
        process.env.REDIS_PORT
    );
    
    redisInstance.init();
}

而你是 console.log 错误值


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.redisport)
            console.log("host: ", this.redishost)
    
            } catch(error) {
                console.log(`Error creating client due to: ${error}`)
            }
}

【讨论】:

  • 我更新帖子时忘记重命名班级名称。问题仍然存在。
  • 尝试在新 Redis 之前登录并告诉我它是否仍然未定义,在导入时显示更多代码,您尝试使用 dotenv 读取 env 文件
  • 我在新 Redis 之前登录,它有值。当它进入Redis 类时,在构造函数调用之前,它具有值。只有当构造函数被调用时,值是未定义的。
  • 对不起,我不明白
  • 当你说声明你指的是什么时?你能更新你的代码给我看看吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-17
相关资源
最近更新 更多