无法在阿波罗服务器上下文中获取会话?
Posted
技术标签:
【中文标题】无法在阿波罗服务器上下文中获取会话?【英文标题】:Cannot get sessions in apollo server context? 【发布时间】:2021-04-29 18:35:55 【问题描述】:我遇到了这个问题:
我无法访问 apollo 服务器上下文中请求对象中的会话对象,因此我得到未定义为输出。 否则我可以正常访问快速路由内的请求对象中的会话对象。我该如何解决?
import express, Application, Request, Response from 'express';
import bodyParser from "body-parser";
import helmet from "helmet";
import xss from 'xss';
import moment from "moment";
import passport from "passport";
import connect from "mongoose";
import "reflect-metadata";
import ApolloServer from 'apollo-server-express';
import buildSchema, ResolverData from "type-graphql";
// Import resolvers
import main_config from './main.config';
import AuthenticationRoutes from './Authentication/Authentication.routes';
import './Authentication/Authentication.strategies';
import
topicResolver, docsResolver, courseResolver, articleResolver, projectIdeaResolver
from './Graphql/Topics/Topics.resolvers';
import cookieSession from 'cookie-session';
import expressSession from 'express-session';
// const expGql = require("express-graphql");
const app : Application = express();
// Init cookie cookie-session
app.use(cookieSession(
keys : ["IDFVBHNIOVFFBUE"],
name : 'DBDIUN',
secret : "IDFVBHNIOVFFBUE"
));
async function runapp ()
// Ïnit passport app and routes
app.use(passport.initialize());
app.use(passport.session())
// Run apollo server
const apollo = new ApolloServer(
schema : await buildSchema(
resolvers : [
topicResolver, docsResolver, courseResolver, articleResolver, projectIdeaResolver
],
globalMiddlewares: [],
),
context: ( req, res ) =>
console.log("context")
console.log(req.session.passport) // cannot get session object then Get undefined
return
getUser: () => req.user,
logout: () => req.logout(),
,
playground : true
)
apollo.applyMiddleware( app );
// Init body parser and helmet
app.use(helmet());
app.use(bodyParser.json());
app.use('/auth', AuthenticationRoutes)
runapp();
【问题讨论】:
【参考方案1】:不要解构 req
为我工作:
context: (req, res) =>
return
req: req,
res: res,
;
【讨论】:
以上是关于无法在阿波罗服务器上下文中获取会话?的主要内容,如果未能解决你的问题,请参考以下文章