首页 > 解决方案 > 节点快速会话反应:服务器cookie未发送到客户端

问题描述

亲爱的,

我在 React 中创建的 https 客户端在调用服务器 graphql 突变时不接收在服务器上创建的 cookie(node.js 应用程序,使用 express-session)。

双方都是https,服务器运行在端口443 https://localhost:443,客户端运行在端口3000 https://localhost:3000

当我运行 graphql 游乐场端点 ( https://localhost:443/graphql ) 时,graphql 工具会收到 cookie。

但是当我使用 apollo 从客户端调用 graphql 突变时,客户端接收到数据,而不是 cookie ......

因此,我假设问题与服务器和客户端之间不同的端口有关,但我尝试了 cookie 参数“sameSite”和“secure”的所有配置。无论这 2 个布尔值的组合如何,客户端都不会收到 cookie。

有没有其他参数可以设置?

这是节点快速会话代码(会话存储在redis存储中)

谢谢。

app.use(cors({ origin: 'https://localhost:3000', credentials: true }));
app.use(session({
    store,
    name: SESSION_NAME,
    secret: SESSION_SECRET,
    resave: false,
    saveUninitialized: false,

    cookie: {
        maxAge: parseInt(SESSION_LIFETIME),
        sameSite: !IN_DEV,
        secure: !IN_DEV
    },
}));

[编辑 - 在 Daniel Rarden 的帮助下解决了问题]

这是服务器端和客户端的代码,可以解决所有问题。

服务器端:

//  generation sessions
app.use(session({
    store,
    name: SESSION_NAME,
    secret: SESSION_SECRET,
    resave: false,
    saveUninitialized: false,

    cookie: {
        maxAge: parseInt(SESSION_LIFETIME),
        httpOnly: true,
        sameSite: true,
        secure: !IN_DEV,
    },
}));

app.use(cors({ origin: 'https://localhost:3000', credentials: true }));

// should be added to avoid CORS issue after executing the Grahql queries
res.setHeader("Access-Control-Allow-Origin", "https://localhost:3000");
const apolloServer = new ApolloServer({
    typeDefs,
    resolvers,

    //     //  permet de tester grqphql. 
    //     //  settings permet de gerer en dev les cookies
    playground: IN_DEV ? {
        settings: { 'request.credentials': 'include' }
    } : false,
    context: ({ req, res }) => ({ req, res })
});
apolloServer.applyMiddleware({ app });

客户端

import { ApolloClient } from 'apollo-client';
import { createHttpLink } from 'apollo-link-http'
import { InMemoryCache } from 'apollo-cache-inmemory'
const link = createHttpLink({
    uri: "https://localhost/graphql",
    credentials: 'include'
});

export const apolloClient = new ApolloClient({
    link,
    cache: new InMemoryCache({ addTypename: false })
});

标签: reactjscookieshttpsgraphqlexpress-session

解决方案


推荐阅读