【问题标题】:GraphQL Explorer not working with Express SessionsGraphQL Explorer 无法与 Express 会话一起使用
【发布时间】:2021-12-04 02:40:43
【问题描述】:

我正在尝试使用 GraphQL 和 Express 创建登录系统,但会话未保存。每当我登录时,req.session.userId 都保持未定义状态。

我的代码:

(async () => {
    await connect(process.env.MONGO_URI!, { dbName: "example" });

    const app = express();

    app.use(
        cors({
            origin: [__clientUrl__, "https://studio.apollographql.com"],
            credentials: true
        })
    );

    app.use(
        session({
            name: "qid",
            secret: process.env.SESSION_SECRET!,
            store: MongoStore.create({
                mongoUrl: process.env.MONGO_URI,
                dbName: "example"
            }),
            saveUninitialized: false,
            resave: false,
            cookie: {
                maxAge: 6.048e8,
                httpOnly: __prod__,
                sameSite: "lax",
                secure: __prod__
            }
        })
    );

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

    await server.start();

    server.applyMiddleware({
        app,
        cors: {
            origin: [__clientUrl__, "https://studio.apollographql.com"],
            credentials: true
        }
    });

    app.listen(__port__, () =>
        console.log(
            `???? Server started at http://localhost:${__port__}${server.graphqlPath}`
        )
    );
})();

TypeGraphQL 登录突变:

    @Mutation(() => User, { nullable: true })
    public async login(
        @Arg("username") username: string,
        @Arg("password") password: string,
        @Ctx() { req }: Context
    ) {
        const user = await UserModel.findOne(
            username.includes("@") ? { email: username } : { username }
        );
        if (!user) return;

        if (!(await verify(user.password, password))) return;

        req.session.userId = user._id;

        return user;
    }

我还在 GraphQL Explorer 中启用了 cookie 并设置了以下标题:

【问题讨论】:

    标签: typescript express session graphql express-graphql


    【解决方案1】:

    你找到解决办法了吗? 您可以尝试通过在创建服务器时添加插件 ApolloServerPluginLandingPageGraphQLPlayground 来使用“旧”playgound

    plugins: [ ApolloServerPluginLandingPageGraphQLPlayground(), ],
    

    如果这适用于“旧”游乐场,则问题出在 graphqlstudio。

    AFAIC,无论我传递给服务器的 cors 值如何,我都面临 graphql studio 的 cors 问题。于是我放弃了graphql studio,回到了playground

    【讨论】:

    • 别担心,我想我找到了一种可行的方法。感谢您的意见!
    • 您介意分享您的代码和设置吗? cors 仍然存在问题
    【解决方案2】:

    我做了一些研究,发现当你创建 ApolloServer 实例时我需要写这个:

        const server = new ApolloServer({
            schema: await buildSchema({
                resolvers: [HelloResolver, UserResolver],
                validate: false
            }),
            context: ({ req, res }) => {
    >           res.header(
    >               "Access-Control-Allow-Origin",
    >               "https://studio.apollographql.com"
    >           );
    >           res.header("Access-Control-Allow-Credentials", "true");
    
                return { req, res };
            }
        });
    

    这允许在 GQL Explorer 中设置 cookie。让我知道这是否适合您!

    【讨论】:

    • 你为什么要设置两次cors?
    • 哦,我删除了。没有必要。
    猜你喜欢
    • 2016-02-28
    • 2019-02-16
    • 2018-06-12
    • 2018-06-03
    • 1970-01-01
    • 2016-12-25
    • 2015-01-16
    • 1970-01-01
    • 2016-08-27
    相关资源
    最近更新 更多