连接Redis和Express会话

htzpubme  于 12个月前  发布在  Redis
关注(0)|答案(2)|浏览(165)

我正在尝试这样做,但我的项目使用ES6,我遇到了问题。下面是我如何声明和开始:

import session from 'express-session';
import connectRedis from 'connect-redis';
import { createClient } from 'redis';

const app = express();

async function startServer() {
    const redisURL = 'redis://localhost:6379';
    const redisClient = createClient();
    const RedisStore = connectRedis(session);
    await redisClient.connect({ url: redisURL });
    const store = new RedisStore({ redisClient });

    app.use(session({
        store: store ,
        secret: process.env.SESSION_SECRET
        resave: false,
        saveUninitialized: false,    
        cookie: { 
            httpOnly: true, 
            path: '/', 
            sameSite: 'strict',
            expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000) 
        }
    }));
}

字符串
D:\AI Projects\Hplayer - Copy\server\server.js:33 RedisStore =(0,_connectRedis[“default”])(_expressSession[“default”]); ^
TypeError:类构造函数RedisStore不能在没有'new'的情况下调用
有什么想法吗?
连接Redis和Express会话

jaql4c8m

jaql4c8m1#

import { createClient } from 'redis';

const client = createClient({
    password: '*******',
    socket: {
        host: 'redis-10352.c292.ap-southeast-1-1.ec2.cloud.redislabs.com',
        port: 10352
    }
});

字符串
我使用了云Redis DB。连接成功。我使用了云,因为我没有本地Redis安装。你必须像这样创建客户端。

import RedisStore from 'connect-redis';
import express from 'express';
import session from 'express-session';
import { createClient } from 'redis';

const redisURL = 'redis://localhost:6379';
const app = express();
const redisClient = createClient({ url: redisURL });
redisClient.connect().catch(console.error);
app.use(
  session({
    store: new RedisStore({
      client: redisClient,
    }),
    resave: false,
    saveUninitialized: false,
    secret: 'yoursecrethereabcxyz',
    cookie: {
      httpOnly: true,
      path: '/',
      sameSite: 'strict',
      expires: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),
    },
  })
);

app.get('/', (req, res) => {
  res.send('Running');
});

const PORT = 1234;

app.listen(PORT, () => {
  console.log(`Server is running on http://localhost:${PORT}`);
});


这里是解决方案.你不需要调用connectRedis与会话作为一个参数.它将像这样工作.如果这不工作,那么可能有一个问题与url或redis权限

gcuhipw9

gcuhipw92#

Node Redis在对createClient的调用中接收到它的配置,而不是对.connect的调用。你需要像这样连接:

const redisClient = createClient({ url: redisURL });
await redisClient.connect();

字符串
这可能不是你的问题的核心,但它是不正确的东西。你可能会逃脱它,因为如果你没有传递任何东西给XNUMX客户端,它会假设主机为localhost,端口为6379

相关问题