1

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

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`);
});
4

2 回答 2

2

来自 Express文档

中间件加载的顺序很重要:首先加载的中间件函数也会先执行。

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

于 2020-04-24T21:37:19.177 回答
1

我认为您必须在开发过程中将 cookie 安全设置为错误,如下所示:

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 
        }
    })
);

于 2021-12-31T10:09:10.753 回答