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