快速 会话 和 连接 redis 保存 会话 redis 存储 时 出错 ( 类型 错误 :此 . client.set 不是 函数 )

vlju58qv  于 2022-11-21  发布在  Redis
关注(0)|答案(1)|浏览(186)

我正在尝试实现express-session和connect-redis来管理节点应用程序的会话。
我已经按照说明使用connect-redis应用express-session了
app.js

import express from "express";
import http from "http";
import session from "express-session";
import connectRedis from "connect-redis";

const app = express();
const StoreRedis = connectRedis(session);

sessionConfig.setStorage(new StoreRedis({ client: redisService() }));

app.use(session(sessionConfig.getConfig()));

const server =
    appConfig.SECURE == true
      ? https.createServer({}, app)
      : http.createServer(app);

app.use("/", router);

  server.listen(appConfig.GAME_SERVICE_PORT, appConfig.SERVER_HOST, () => {
    const protocol = appConfig.SECURE == true ? "https" : "http";
    console.log(
      `Server started ${protocol}://${appConfig.SERVER_HOST}:${appConfig.GAME_SERVICE_PORT}`
    );
  });

redis-service.js

import { createClient } from "redis";
export default async () => {
  // redis[s]://[[username][:password]@][host][:port][/db-number]
  const redisClient = createClient({
    // url: `redis://${REDIS_USERNAME}:@${REDIS_PASSWORD}${REDIS_HOST}:${REDIS_PORT}`,
    legacyMode: true,
  });

  redisClient.on("error", function (err) {
    console.log("Could not establish a connection with redis. " + err);
  });
  redisClient.on("connect", function (err) {
    console.log("Connected to redis successfully");
  });

  await redisClient.connect();

  return redisClient;
};

route.js

export default (request, response, next) => {
  request.session.key = "aaaaa";
  response.render("game", {
    title: "title of the game",
  });
};

当我尝试访问路由的URL时,给予此错误

当我尝试将数据保存到Redis时,它可以保存数据

await redisClient.set("input", "value");

我的问题出在Redis商店。
package.json节点版本16.16.0

谢谢你的帮助。

lskq00tm

lskq00tm1#

redisService()会传回Promise<RedisClient>,但StoreRedis预期client会是RedisClient
我非常肯定,如果您可以使用import,您也可以使用top-level-await,因此我将在下面的解决方案中使用它:

// `redis-service.js`
import { createClient } from 'redis';

const client = createClient({
  // ...
  legacyMode: true
});

client.on('error', (err) => console.log('Could not establish a connection with redis', err));
client.on('connect', () => console.log('Connected to redis successfully'));

await client.connect();

export default client;

// `app.js`
// ...
import redisClient from './redis-service.js';
// ...
sessionConfig.setStorage(new StoreRedis({ client: redisClient }));
// ...

相关问题