尝试从 nuxt 3 中间件连接到 redis 客户端,但连接未定义是什么原因呢?

我正在尝试连接到 redis 服务器以从 nuxt 3 defineNuxtRouteMiddleware 中间件获取我的会话数据,但没有成功。我在服务器端插件中创建了与 redis 的连接,它适用于我所有的 api 端点,但它似乎不适用于我的 rout-guards 中间件。我试图在下面的代码中获取连接,但连接未定义。我假设中间件服务器端执行应该可以访问 redis 连接是不正确的

if (process.server) {
     let session =     await RedisUtil.getConnection.    get(sessionID);
}
  • 1.
  • 2.
  • 3.

下面是redisUtil

class RedisUtil{
        static     get getConnection(){
            return this.connection;
    }

        static     set setConnection(connection){
        this.connection = connection;
    }

        static     async connect(config) {
            let redis = createClient({
            url: 'redis://' + config.redis.user + ':' + config.redis.password + '@' + config.redis.host + ':' + config.redis.port
        });

        redis.on('error', err console.log('Redis Client Error', err));

            await redis.connect();
        RedisUtil.setConnection = redis;
        console.log("Connected to redis");
    }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.

redis 插件加载到 nitro 配置中

import RedisUtil     from '../utils/RedisUtil';
    import config     from "~/server.config"    export     default     async (NuxtApp) => {
        await RedisUtil.connect(config);
};
  • 1.
  • 2.
  • 3.
  • 4.
nitro: {
        plugins: [
                "~/server/plugins/redis.js"
            ],
    },
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.

如上所述,我能够在所有其他服务器端执行中访问 redis 连接,但不能在中间件中访问。对此的任何帮助将不胜感激。

vue.js
redis
middleware
2023-04-21 14:27:11
3746浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
阿卡林95

你似乎只在服务器端部分运行 Redis 请求。当客户端路由发生时,让它失去上下文。

export default defineNuxtRouteMiddleware(    async (to,     from) => {
      let session = '';
      if (process.server) {
    session = 'has some context';
  }

  // server: session = 'has some context'
  // client: session = ''
})
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
已于2023-4-21 16:43:19修改
分享
微博
QQ
微信
回复
2023-04-21 16:43:10


相关问题
golang redis客户端连接状态
3526浏览 • 1回复 待解决
HarmonyOS 客户端向远端设备发起spp连接
1441浏览 • 1回复 待解决
中间件什么特点有知道的吗?
3950浏览 • 1回复 待解决
开源的中间件能否在PolarDB中使用?
3269浏览 • 1回复 待解决
HarmonyOS项目字段未定义问题
916浏览 • 1回复 待解决
如何使用ssl连接到PolarDB ?
3787浏览 • 1回复 待解决
地图定位不准,是什么原因啊?
786浏览 • 1回复 待解决
mysql客户端怎么开启预编译?
3831浏览 • 1回复 待解决
客户端开发无法获取code
1177浏览 • 1回复 待解决