【问题标题】:React, Graphql & Passport.jsReact、Graphql 和 Passport.js
【发布时间】:2019-08-16 09:32:55
【问题描述】:

我正在尝试使用 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,
});

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

【问题讨论】:

    标签: node.js reactjs graphql passport.js apollo-client


    【解决方案1】:

    以防万一有人遇到同样的问题,我们需要解决一些问题才能使其正常工作:

    在客户端:

    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 }
    });
    

    它对我有用:)

    【讨论】:

    • 感谢您澄清这一点。我在这方面工作了一段时间,但在服务器端工作但在客户端却没有同样的错误。现在一切都好!
    猜你喜欢
    • 1970-01-01
    • 2019-09-06
    • 2017-09-01
    • 2014-07-16
    • 2014-03-22
    • 2018-10-11
    • 1970-01-01
    • 2021-04-04
    • 2018-02-12
    相关资源
    最近更新 更多