未在生产中设置会话

时间:2019-12-13 04:31:13

标签: node.js express bitnami apollo-server express-session

我正在使用Express和Apollo服务器构建服务器,在本地开发时一切正常,但是在生产会话中未将其设置为浏览器时,但是当我在Redis数据库中可以看到会话密钥时,运行keys *。我的React应用程序不断收到401状态代码,因此我无法登录。

所以我想知道为什么在Redis中存储会话密钥,而实际上未设置会话。在本地检查元素时,我可以看到cookie作为会话ID,但不能在生产环境中看到。我正在使用在Bitnami创建的ubuntu上运行的apache网络服务器。任何帮助将不胜感激。

这是我的密码

const RedisStore = connectRedis(session);

const bootstrap = async () => {
    //Db connection.
    await createConnection();
    //cron jobs.
    registerCronJobs();
    //Init Firebase
    initFirebase();

    const store = new RedisStore({
        client: redis as any,
        logErrors: true
    });

    const apolloServer = new ApolloServer({
        schema: await createSchema(),
        context: ({req, res}: any) => ({req, res}),
        //introspection: true //turn it on later when other developers can take part.
    });

    const app = express();

    app.use(helmet());

    app.use(cors({
        credentials: process.env.NODE_ENV !== "production",
        origin: ['http://localhost:3000'] //React app.
    }));

    app.set('trust proxy', process.env.NODE_ENV === "production");

    app.use(session({
        store,
        name: COOKIE_NAME,
        secret: config.get('session_secret'),
        resave: false,
        saveUninitialized: false,
        cookie: {
            httpOnly: true,
            secure: process.env.NODE_ENV === "production",
            maxAge: 1000 * 60 * 60 * 24 * 30 // 1 month
        }
    }));

    app.use(bodyParser.urlencoded({extended: false}));
    app.use(bodyParser.json());
    app.use(express.static(path.join(__dirname, '..', 'public/web/build')));
    app.use(bridgeRouter);

    const httpServer = http.createServer(app);
    const PORT = process.env.port || 2000;

    // ref : https://dev.to/tmns/session-handling-in-react-with-redux-express-session-and-apollo-18j8
    apolloServer.applyMiddleware({app, cors: false});
    apolloServer.installSubscriptionHandlers(httpServer);

    app.get('*', function (_req: Request, res: Response) {
        res.sendFile(path.join(__dirname, '..', 'public/web/build', 'index.html'));
    });

    //`listen` on the http server variable, and not on `app`.
    httpServer.listen(PORT, () => {
        console.log(`Server ready at http://localhost:${PORT}${apolloServer.graphqlPath}`);
        console.log(`Subscriptions ready at ws://localhost:${PORT}${apolloServer.subscriptionsPath}`);
    })
};

bootstrap().catch(e => console.log(e));

0 个答案:

没有答案