Windows环境下Express.js无法从WSL2的Redis获取键值问题
问题
Windows 10系统上运行的Node.js Express应用(部署在localhost:3500),使用WSL2中运行的Redis服务器(localhost:6379)存储刷新令牌。目前能成功向Redis写入键值对,但无法通过键获取对应值,请问原因是什么?
提供的代码
Redis客户端代码
const redis = require('redis'); const client = redis.createClient({ port:"6379", host:"127.0.0.1" }); client.connect().then(() => { console.log("Redis connected !!"); }).catch((err) => { console.log(err.message); const errr = new Error("Internal server error"); errr.status = 500; next(errr); }); client.on('connect',() => { console.log("Client connected to redis !!"); }); module.exports = client;
Express应用代码(app.js)
// Importing dependencies const express = require('express'); const mongoose = require('mongoose'); const authRouter = require('./routes/authRoutes'); const cors = require('cors'); const cookieParser = require('cookie-parser'); require('dotenv').config(); const client = require('./Helpers/redisConn'); const app = express(); client.set('foos','bars'); client.get('foos',(err,val) => { if(err){ console.log(err.message); } console.log(val); }); ....
可能的原因与解决方案
异步操作顺序问题:你用的是redis@4.x版本,这个版本的
set和get都是异步Promise方法,但你直接同步调用client.get,此时set操作可能还没完成,自然拿不到值。
解决方法:改用异步链式调用或者async/await:// 链式调用写法 client.set('foos','bars') .then(() => client.get('foos')) .then(val => console.log(val)) // 输出bars .catch(err => console.log(err.message));或者:
// async/await写法 async function testRedisOps() { await client.set('foos','bars'); const val = await client.get('foos'); console.log(val); } testRedisOps();WSL2与Windows的网络隔离问题:WSL2的
localhost和Windows的localhost属于不同的网络命名空间,你以为连的是WSL2的Redis,可能实际连的是Windows本地的Redis(如果装了的话),导致写和读不在同一个实例里。
解决方法:- 修改WSL2里的Redis配置文件(通常在
/etc/redis/redis.conf),把bind 127.0.0.1改成bind 0.0.0.0,然后重启Redis服务(sudo service redis restart)。 - 在Windows的Express应用中,把Redis客户端的host改成WSL2的实际IP地址(在WSL2终端执行
hostname -I获取),比如host: "192.168.1.100",而不是127.0.0.1。
- 修改WSL2里的Redis配置文件(通常在
Redis键值检查:直接在WSL2终端里进入Redis-cli,执行
KEYS *查看是否存在foos键,再用GET foos看值是否正确。如果键不存在,说明写入操作根本没到WSL2的Redis;如果键存在但应用里拿不到,再排查客户端编码或连接问题。
额外代码问题提示
你的Redis客户端连接代码中,catch块里的next是未定义的(这个文件没有Express的请求上下文),运行时会报错,建议修改为:
client.connect().then(() => { console.log("Redis connected !!"); }).catch((err) => { console.log("Redis连接失败:", err.message); });
内容的提问来源于stack exchange,提问作者Study Planet
相关产品推荐
相关产品推荐

