首页 > 解决方案 > 为什么 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”属性更改为“包含”来解决。

标签: javascriptnode.jsexpresssessionredis

解决方案


推荐阅读