node.js - express-session不设置cookie?

我正在关注 Ben Awad's 13-hour Fullstack React GraphQL TypeScript Tutorial并在登录 cookie 设置期间遇到墙(aprx 在 1:50:00)。

我认为我已成功连接到 redis,设置了 express-session 并设置了请求类型,但在 graphql 沙箱中,我在 Inspect->Application 中看不到我的 cookie(名为“qid”)。

索引.ts

import { MikroORM } from "@mikro-orm/core";
import { __prod__ } from "./constants";
import microConfig from "./mikro-orm.config";
import express from "express";
import { ApolloServer } from "apollo-server-express";
import { buildSchema } from "type-graphql";
import { HelloResolver } from "./resolvers/hello";
import { PostResolver } from "./resolvers/post";
import { UserResolver } from "./resolvers/user";
import redis from "redis";
import session from "express-session";
import connectRedis from "connect-redis";

const main = async () => {
  const orm = await MikroORM.init(microConfig);
  await orm.getMigrator().up();

  const app = express();

  const RedisStore = connectRedis(session);
  const redisClient = redis.createClient();

  app.use(
    session({
      name: "qid",
      store: new RedisStore({
        client: redisClient,
        disableTouch: true,
      }),
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 365 * 10,
        httpOnly: true,
        sameSite: "none",
        // secure: __prod__,
      },
      saveUninitialized: false,
      secret: "dfhfdjkgfkbjktzkzf",
      resave: false,
    })
  );

  app.use(function (req, res, next) {
    res.header(
      "Access-Control-Allow-Origin",
      "https://studio.apollographql.com"
    );
    res.header("Access-Control-Allow-Credentials", "true");
    next();
  });

  const apolloServer = new ApolloServer({
    schema: await buildSchema({
      resolvers: [HelloResolver, PostResolver, UserResolver],
      validate: false,
    }),
    context: ({ req, res }) => ({ em: orm.em, req, res }),
  });

  await apolloServer.start();
  apolloServer.applyMiddleware({
    app,
    cors: {
      credentials: true,
      origin: new RegExp("/*/"),
    },
  });

  app.listen(4000, () => {
    console.log("server started on port 4000");
  });
};

main();

类型.ts

import { EntityManager, IDatabaseDriver, Connection } from "@mikro-orm/core";
import { Request, Response } from "express";
import { Session, SessionData } from "express-session";

export type MyContext = {
  em: EntityManager<any> & EntityManager<IDatabaseDriver<Connection>>;
  req: Request & {
    session: Session & Partial<SessionData> & { userId: number };
  };
  res: Response;
};

和我的 userResolver (user.ts)

import { User } from "../entities/User";
import { MyContext } from "../types";
import {
  Arg,
  Ctx,
  Field,
  InputType,
  Mutation,
  ObjectType,
  Query,
  Resolver,
} from "type-graphql";
import argon2 from "argon2";

@InputType()
class UsernamePasswordInput {
  @Field()
  username: string;

  @Field()
  password: string;
}

@ObjectType()
class FieldError {
  @Field()
  field: string;

  @Field()
  message: string;
}

@ObjectType()
class UserResponse {
  @Field(() => [FieldError], { nullable: true })
  errors?: FieldError[];

  @Field(() => User, { nullable: true })
  user?: User;
}

@Resolver()
export class UserResolver {


  @Mutation(() => UserResponse)
  async login(
    @Arg("options", () => UsernamePasswordInput) options: UsernamePasswordInput,
    @Ctx() { em, req }: MyContext
  ): Promise<UserResponse> {
    const user = await em.findOne(User, { username: options.username });
    if (!user) {
      return {
        errors: [
          {
            field: "username",
            message: "username does not exist",
          },
        ],
      };
    }
    const valid = await argon2.verify(user.password, options.password);
    if (!valid) {
      return {
        errors: [
          {
            field: "password",
            message: "incorrect password",
          },
        ],
      };
    }

    req.session.userId = user.id;

    return {
      user,
    };
  }
}

我尝试按照 graphql 沙箱的要求设置 res.headers,但仍然无济于事。非常感谢任何帮助,谢谢!

最佳答案

好吧,我不确定发生了什么,但我似乎解决了这个问题。

我的想法是:GraphQL Playground 已退休,localhost:port/graphql 现在重定向到 Apollo GraphQL Sandbox 到不同的 url,我的猜测是 cookie 不会传输到此位置,但 cookie 设置在 localhost。

所以有一种方法可以强制 Apollo 继续使用 Playground,方法是添加:

import { ApolloServerPluginLandingPageGraphQLPlayground } from "apollo-server-core";


  const apolloServer = new ApolloServer({
    ...,
    plugins: [
      ApolloServerPluginLandingPageGraphQLPlayground({
        // options
      }),
    ],
  });

这样 Playground 就会出现,你可以设置

  "request.credentials": "include",

在设置中,瞧,cookie 显示在 localhost:port。

我希望这对解决此问题的任何人有所帮助 - 但我仍然不确定这是一个正确的解决方案。

https://stackoverflow.com/questions/69333408/

相关文章:

ruby-on-rails - Rails 参数方法 : Why can it be accesse

python - Linux Mint Cinnamon 错误打开设置(没有名为 'PIL' 的模块

assembly - 如果 x86 jmp 跳转到其他两个连续有效地址之间的地址会发生什么?

visual-studio-code - 如何在VSC终端创建文件?

javascript - MongooseServerSelectionError:连接 ECONN

c++ - 嵌套 std::map 的单行查找

python - python解释器是否隐含地使用了中国余数定理?

reactjs - 如何更改Chakra UI Toast组件的背景颜色?

r - 从 R 中的数据帧列表中进行子集化

indexing - 为什么索引 HashMap 不返回引用?