javascript - 为什么 Express Session 变量 (userID) 不在浏览器中创建 cookie?
问题描述
我用 Express Session 和 Redis 创建了一个简单的服务器。Redis 服务器正在运行(当我输入“redis-cli ping”时收到“PONG”),我声明了命名空间并导出了接口 SessionData 以允许我将 userID 存储在 req.session 上(使用基本的 index.d. ts)。但是,当我发出登录请求时,变量 userID 存储在 req.session 中,但由于 cookie 未设置到浏览器,因此立即被遗忘/删除。似乎每个请求都会产生一个新会话并且 cookie 永远不会保存。
App、Redis 和 Session Cookie 设置:
// ...
const app = express();
const RedisStore = connectRedis(session);
const redis = new Redis();
app.use(
session({
name: 'testcookie',
store: new RedisStore({
client: redis,
disableTouch: true,
port: 6379,
host: 'localhost',
}),
cookie: {
maxAge: 36000000 * 24 * 365,
httpOnly: true,
sameSite: 'lax',
secure: false,
},
saveUninitialized: false,
secret: 'secret',
resave: false,
})
);
// ...
登录突变:
@Mutation(() => UserResponse)
async login(
@Arg("usernameOrEmail") usernameOrEmail: string,
@Arg("password") password: string,
@Ctx() { req }: MyContext
): Promise<UserResponse> {
// gets user via inputs (everything works here)
// ...
req.session.userID = user.id;
// userID is set to be a number, as is user.id
// logging req.session.userID works perfectly if done right here
return { user };
}
查询是否已登录:
@Query(() => User, { nullable: true })
async me(@Ctx() { req }: MyContext): Promise<User | undefined> {
// logging req.session.userID shows undefined
return (req.session.userID)
? await User.findOne({ id: req.session.userID })
: undefined;
}
更新(解决方案):这已通过进入 GraphQL 的设置并将“request.credentials”属性更改为“包含”来解决。
解决方案
推荐阅读
- android - 告诉 ProGuard 不要保留某些东西
- javascript - 包含 getAttribute 的函数没有返回
- typescript - 经典的“省略”功能,类似的代码以通常的方式编写和使用柯里化编写时完全不同的打字结果,我错过了什么?
- mysql - 如何只获取第一级深度子节点?
- php - 如何在wordpress添加短代码的返回部分添加循环?
- linux - 如何访问服务器地址
- modal-dialog - Laravel 8 使用模态更新数据
- tensorflow - 多元 GMM TensorFlow 实现
- reactjs - 单击按钮时页面未滚动到顶部
- flutter - 如何在 Flutter 中自定义 file_picker UI