首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >React,Graphql & Passport.js

React,Graphql & Passport.js
EN

Stack Overflow用户
提问于 2019-03-26 12:09:17
回答 1查看 198关注 0票数 0

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

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

我的一些配置如下:

我已经尝试在客户端和服务器端更改凭据

服务器配置

代码语言:javascript
复制
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 });

客户端配置

代码语言:javascript
复制
const cache = new InMemoryCache();
const link = new HttpLink({
    uri: 'http://localhost:4000/graphql',
    credentials: 'same-origin',
});

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-03-29 08:50:23

为了防止任何人遇到同样的问题,我们需要解决几个问题才能使其正常工作:

在客户端中:

代码语言:javascript
复制
const link = createHttpLink({
    uri: 'http://localhost:4000/graphql',
    credentials: 'include',
});

在服务器中:

代码语言:javascript
复制
// 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 }
});

它对我很有效:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55349719

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档