我正在嘗試使用 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 并設定了這些標題:

uj5u.com熱心網友回復:
你找到解決辦法了嗎?您可以在創建服務器時通過添加插件 ApolloServerPluginLandingPageGraphQLPlayground 來嘗試使用“舊”游戲場
plugins: [ ApolloServerPluginLandingPageGraphQLPlayground(), ],
如果這適用于“舊”游樂場,則問題出在 graphqlstudio 中。
AFAIC,無論我傳遞給服務器的 cors 值是什么,我都面臨著 graphql studio 的 cors 問題。所以我放棄了 graphql 作業室并回到了操場
uj5u.com熱心網友回復:
我做了一些研究,并意識到我需要在創建 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。讓我知道這是否適合您!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/321909.html
標籤:打字稿 表达 会议 图形 express-graphql
