无法在我的突变中使用快速会话

Can't use express session in my mutations

大家好,我对快速会话有疑问。我已经使用 express-session 创建了我的会话并在我的 apollo-server-express 中使用了它但是在我的登录突变中当我想使用会话来存储我的用户 ID 并再次在我的查询中使用该会话时,它将变为未定义.有什么问题?

这是我的 index.js 我使用 mongo-connect:

创建会话的地方
const MongoStore = mongoconnect(session);    
const SERVER = new ApolloServer({
    typeDefs,
    resolvers,
    cors: {
        origin: '*',
        credentials: true
    },
    playground: {
        endpoint: `http://localhost:3600/graphql`,
        settings: {
            'editor.theme': 'dark'
        }
    },
    context: ({ req }) => {
        return {
            req,
            session: req.session
        }
    }
});

app.use(
    session({
        store: new MongoStore({
            mongooseConnection: mongoose.connection
        }),
        secret: "mysecret-ssss",
        resave: false,
        saveUninitialized: false,
        cookie: {
            maxAge: 1000 * 60 * 60 * 2,
            sameSite: true,
            secure: true
        }
    })
);

这是我的查询:

Query: {
   circularLetters: async (parent, args, context, info) => {
            const options = {
                page: args.page,
                limit: args.limit
            };
            const circularLetter = await CircularLetters.paginate({}, options, (err, result) => {
                return result.docs;
            });
            console.log(context.session.userId)

            return circularLetter;
        },
}

我想在会话中存储我的用户 ID 的地方:

Mutation: {
     login: async (parent, args, context, info) => {
            const user = await Users.findOne({
                personelNumber: args.data.personelNumber
            }, function (err, myUser) {
                console.log(err);
            });

            if (!user) {
                throw new Error("User not found");
            }

            const isMatch = await bcrypt.compare(args.data.password, user.password);

            if (!isMatch) {
                throw new Error("Wrong password");
            }

            context.session.userId = user.id;
            console.log(context.session);

            return {
                user,
                token: generateToken(user.id)
            }
        },
}

确定找到解决方案。这是关于 Apollo 的,你必须在 Apollo 中阻止 Cors 并像这样导入 Cors:

import cors from 'cors';

const SERVER = new ApolloServer({
    typeDefs,
    resolvers,
    engine: {
        debugPrintReports: true
    },
    playground: {
        endpoint,
        settings: {
            'editor.theme': 'dark'
        }
    },
    context: ({ req, res }) =>
        ({
            req,
            res,
            session: req.session
        })
});

app.use(cors({
    credentials: true,
    origin: true
}));

app.use(cookieParser());

SERVER.applyMiddleware({
    app,
    cors: false
});