Apollo-server-express Session 未定义问题

Posted

技术标签:

【中文标题】Apollo-server-express Session 未定义问题【英文标题】:Apollo-server-express Session undefined problem 【发布时间】:2020-08-08 10:41:55 【问题描述】:

您好,我想与 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`);
);

【问题讨论】:

【参考方案1】:

来自快递docs:

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

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

【讨论】:

谢谢兄弟你救了我【参考方案2】:

我认为你必须像这样在开发过程中将 cookie 安全设置为 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 
        
    )
);

【讨论】:

以上是关于Apollo-server-express Session 未定义问题的主要内容,如果未能解决你的问题,请参考以下文章

Apollo-Server-Express 未收到上传对象

升级到 apollo-server-express 2.0.0 缺少上下文

是否可以将 apollo-server-express 部署到 lambda?

在 apollo-server-express 中增加身体限制大小

Apollo-server-express 内省已禁用,但仍然可以通过 websocket 连接

如何选择性地允许 apollo-server-express 中的查询?