Apollo-server-express Session undefined 问题

Apollo-server-express Session undefined problem

你好,我想与 ApolloServer 和 Express 建立会话,但是当我从 req.session 获取控制台日志时,它给了我未定义的信息。有什么问题??当我从 app.get 中的 req.session 获取控制台日志时,我得到了我的结果。在 Mongodb compass 中,我可以找到一个会话部分,但我不知道如何使用它或在其中导入数据。 谁能解决这个问题?

import '@babel/polyfill/noConflict';
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import mongoose, { mongo } from 'mongoose';
import { existsSync, mkdirSync } from 'fs';
import path from 'path';
import { resolvers } from './resolvers';
import { typeDefs } from './typeDefs';
import session from 'express-session';
import mongoconnect from 'connect-mongo';

const MongoStore = mongoconnect(session);

const app = express();

let dbUrl = 'mongodb://localhost:27017/test';
mongoose.connect(dbUrl);
mongoose.Promise = global.Promise;
let db = mongoose.connection;
db.on('error', console.error.bind(console, "DB connection error"));

const SERVER = new ApolloServer({
    typeDefs,
    resolvers,
    cors: {
        origin: '*',
        credentials: true
    },
    playground: {
        endpoint: `http://localhost:3600/graphql`,
        settings: {
            'editor.theme': 'dark'
        }
    },
    context: ({ req }) => {
        console.log(req.session) //undefined
        return req
    }
});

SERVER.applyMiddleware({
    app
});

existsSync(path.join(__dirname, "../images")) || mkdirSync(path.join(__dirname, "../images"));

app.use("/images", express.static(path.join(__dirname, "../images")));

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*"); // update to match the domain you will make the request from
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});

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

app.get('/', function (req, res, next) {

});

app.post('/', function (req, res, next) {
    // Handle the post for this route
});

app.listen(3600, () => {
    console.log(`Server ready at port 3600`);
});

来自快递docs:

The order of middleware loading is important: middleware functions that are loaded first are also executed first.

在应用 ApolloServer 中间件之前,需要先应用您的会话中间件。

我认为您在开发过程中必须将 cookie secure 设置为 false :

app.use(
    session({
        store: new MongoStore({
            mongooseConnection: mongoose.connection,
            url: 'mongodb://localhost:27017/test'
        }),
        secret: "mysecret-ssss",
        resave: false,
        saveUninitialized: false,
        cookie: {
            maxAge: 1000 * 60 * 60 * 2,
            sameSite: true,
            secure: false // in development 
        }
    })
);

或者你可以这样做:

app.use(
    session({
        store: new MongoStore({
            mongooseConnection: mongoose.connection,
            url: 'mongodb://localhost:27017/test'
        }),
        secret: "mysecret-ssss",
        resave: false,
        saveUninitialized: false,
        cookie: {
            maxAge: 1000 * 60 * 60 * 2,
            sameSite: true,
            secure: process.env.NODE_ENV === "development" ? false : true 
        }
    })
);