反应、Graphql 和 Passport.js

React, Graphql & Passport.js

我正在尝试使用 passport.js 设置 graphql,在服务器端似乎一切正常,但在客户端,当我检查当前登录的用户时(req.user) 我得到了未定义,而在服务器端,我得到了当前用户

我是 运行 我的服务器在 localhost:4000 上,客户端在 localhost:3000 上。

我的部分配置如下:

我尝试更改客户端的凭据以及服务器端的 cors

服务器配置

app.use(
    session({
        resave: false,
        saveUninitialized: false,
        secret,
        store: new MongoStore({
            url: MONGO_URI,
            autoReconnect: true
        }),
        cookie: {
            maxAge: 1000 * 60 * 60 * 2
        }
    })
);

const server = new ApolloServer({
    typeDefs,
    resolvers,
    // required for passport req.user access
    playground: { settings: { 'request.credentials': 'include' } },
    // so we have access to app req,res through graphql
    context: ({ req, res }) => ({
        req,
        res
    })
});

server.applyMiddleware({ app });

客户端配置

const cache = new InMemoryCache();
const link = new HttpLink({
    uri: 'http://localhost:4000/graphql',
    credentials: 'same-origin',
});

const client = new ApolloClient({
    cache,
    link,
});

我希望能够在客户端访问获取当前登录的用户(反应)

以防万一有人遇到同样的问题,为了使这项工作正常进行,我们需要解决一些问题:

在客户端:

const link = createHttpLink({
    uri: 'http://localhost:4000/graphql',
    credentials: 'include',
});

在服务器中:

// pass types and resolvers
const server = new ApolloServer({
    typeDefs,
    resolvers,
    // required for passport req.user access
    playground: { settings: { 'request.credentials': 'include' } },
    // so we have access to app req,res through graphql
    context: ({ req, res }) => ({
        req,
        res
    })
});

server.applyMiddleware({
    app,
    cors: { origin: 'http://localhost:3000', credentials: true }
});

它对我有用:)