我收到此错误,显示“TypeError:无法读取未定义的属性(读取“get”)”当我点击 API 来测试我的 API 时,出现此错误 我尝试仔细检查我的主机名密码和端口,结果都是正确的使用 Windows 机器并使用 Redis Labs 进行缓存 我正在使用 Redis 版本"redis": "^3.1.2"
并收到此错误
但是,我还尝试在代码中添加事件侦听器来检查 Redis 是否已正确初始化,并且它还记录“Redis 客户端已连接”
我怎样才能解决这些问题并使事情正常进行?我还尝试使用 Redis 最新版本,它是 4.6.5,具有相同的代码,但它没有记录任何内容,因此,如果我点击 API,它会给我 ClientClosedError: The client is a close 错误再次我仔细检查了我的主机名密码和端口一切都是正确的
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' });
}
});