Why Redis i am getting TypeError: Cannot read properties of undefined (reading 'get') my redis is properly initialized?

huangapple go评论78阅读模式
英文:

Why Redis i am getting TypeError: Cannot read properties of undefined (reading 'get') my redis is properly initialized?

问题

I am getting this error that says "TypeError: Cannot read properties of undefined (reading 'get')" This error came when I hit the API to test my API I tried double checking my hostname password and port and it was all correct I am using Windows machine and using Redis Labs for caching I am using Redis version "redis": "^3.1.2" and getting this error

However, I also tried adding event listeners in my code to check that is Redis is properly initialized or not and it was properly initialized and it also logs "Redis client connected"

How can I fix these problems and make things work? I also tried using Redis latest version which is 4.6.5 with the same piece of code but it was logging nothing therefore if I hit the API it gave me ClientClosedError: The client is a closed error again i double-checked my hostname password and port and it was all correct

import { createClient } from 'redis';

const redisClient = createClient({
port: 16545,
host: 'redis-16545.c305.ap-south-1-1.ec2.cloud.redislabs.com',
password: 'mypass',
});

redisClient.on('ready', () => {
console.log('Redis client connected');
});

redisClient.on('error', (err) => {
console.error('Redis client error:', err);
});

redisClient.on('end', () => {
console.log('Redis client disconnected');
});

router.get('/posts', async (req, res) => {
try {
const cacheKey = posts:${req.query.page || 1};
const cacheTTL = 60;

    const cachedData = await redisClient.json.get(cacheKey, '$');

    if (cachedData) {
        console.log('Data fetched from Redis cache');
        return res.json(cachedData);
    }

    const page = Number(req.query.page) || 1;
    const limit = Number(req.query.limit) || 50;
    const skip = (page - 1) * limit;

    const result = await User.aggregate([
        { $project: { posts: 1 } },
        { $unwind: '$posts' },
        { $project: { postImage: '$posts.post', date: '$posts.date' } },
        { $sort: { date: -1 } },
        { $skip: skip },
        { $limit: limit },
    ]);

    await redisClient.json.set(cacheKey, '$', result, 'EX', cacheTTL);

    console.log('Data fetched from MongoDB and cached in Redis');
    res.json(result);
} catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Internal server error' });
}

});

英文:

I am getting this error that says "TypeError: Cannot read properties of undefined (reading 'get')" This error came when I hit the API to test my API I tried double checking my hostname password and port and it was all correct I am using Windows machine and using Redis Labs for caching I am using Redis version "redis": "^3.1.2" and getting this error

However, I also tried adding event listeners in my code to check that is Redis is properly initialized or not and it was properly initialized and it also logs "Redis client connected"

How can I fix these problems and make things work? I also tried using Redis latest version which is 4.6.5 with the same piece of code but it was logging nothing therefore if I hit the API it gave me ClientClosedError: The client is a closed error again i double-checked my hostname password and port and it was all correct

import { createClient } from 'redis';

const redisClient = createClient({
    port: 16545,
    host: 'redis-16545.c305.ap-south-1-1.ec2.cloud.redislabs.com',
    password: 'mypass',
});

redisClient.on('ready', () => {
    console.log('Redis client connected');
});

redisClient.on('error', (err) => {
    console.error('Redis client error:', err);
});

redisClient.on('end', () => {
    console.log('Redis client disconnected');
});

router.get('/posts', async (req, res) => {
    try {
        const cacheKey = `posts:${req.query.page || 1}`;
        const cacheTTL = 60;

        const cachedData = await redisClient.json.get(cacheKey, '$');

        if (cachedData) {
            console.log('Data fetched from Redis cache');
            return res.json(cachedData);
        }

        const page = Number(req.query.page) || 1;
        const limit = Number(req.query.limit) || 50;
        const skip = (page - 1) * limit;

        const result = await User.aggregate([
            { $project: { posts: 1 } },
            { $unwind: '$posts' },
            { $project: { postImage: '$posts.post', date: '$posts.date' } },
            { $sort: { date: -1 } },
            { $skip: skip },
            { $limit: limit },
        ]);

        await redisClient.json.set(cacheKey, '$', result, 'EX', cacheTTL);

        console.log('Data fetched from MongoDB and cached in Redis');
        res.json(result);
    } catch (err) {
        console.error(err);
        res.status(500).json({ message: 'Internal server error' });
    }
});

答案1

得分: 3

I think the connection is not up to date with the redis new version 4.6.5 changes:

The host + port + password should be in one connection string - url.

The format is:
redis

展开收缩
://[[username][:password]@][host][:port][/db-number]

I guess your connection URL should be:

redis://:mypass@redis-16545.c305.ap-south-1-1.ec2.cloud.redislabs.com:16545

Therefore, to connect to redis do:

import { createClient } from 'redis';

const redisClient = createClient({
    url: 'redis://:mypass@redis-16545.c305.ap-south-1-1.ec2.cloud.redislabs.com:16545'
});

client.on('error', err => console.log('Redis Client Error', err));

await client.connect();

See full documentation here: https://www.npmjs.com/package/redis/v/4.6.5

In the latest Redis version you should call for connect to connect:

await client.connect();

英文:

I think the connection is not up to date with the redis new version 4.6.5 changes:

The host + port + password should be in one connection string - url.

The format is:
redis

展开收缩
://[[username][:password]@][host][:port][/db-number]

I guess your connection URL should be:

redis://:mypass@redis-16545.c305.ap-south-1-1.ec2.cloud.redislabs.com:16545

Therefore, to connect to redis do:
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

import { createClient } from &#39;redis&#39;;

const redisClient = createClient({
    url: &#39;redis://:mypass@redis-16545.c305.ap-south-1-1.ec2.cloud.redislabs.com:16545&#39;
});

client.on(&#39;error&#39;, err =&gt; console.log(&#39;Redis Client Error&#39;, err));

await client.connect();

<!-- end snippet -->

See full documentation here: https://www.npmjs.com/package/redis/v/4.6.5

In the latest Redis version you should call for connect to connect:

await client.connect();

huangapple
  • 本文由 发表于 2023年4月13日 15:06:30
  • 转载请务必保留本文链接:https://go.coder-hub.com/76002562.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定