【问题标题】:How to pass request headers through to graphql resolvers如何将请求标头传递给 graphql 解析器
【发布时间】:2018-09-21 09:29:26
【问题描述】:

我有一个由 JWT 授权的 graphql 端点。我的 JWT 策略验证 JWT,然后将用户对象添加到请求对象。

在一条安静的路线中,我会像这样访问我的用户数据:

router.get('/', (req, res, next) => {
    console.log('user', req.user)
}

我想在我的 graphql 解析器中访问 req.user 对象以提取用户的 ID。但是,当我尝试记录 context 变量时,它始终为空。

我是否需要配置我的 graphql 端点以将 req 数据传递给解析器?

我的 app.js 的 graphql 设置如下:

import { graphqlExpress, graphiqlExpress } from 'apollo-server-express';

app.use('/graphql', [passport.authenticate('jwt', { session: false }), bodyParser.json()], graphqlExpress({ schema }));

然后我有这样的解析器:

const resolvers = {
  Query: { 
    user: async (obj, {email}, context) => {
        console.log('obj', obj) // undefined
      console.log('email', email) // currently passed through in graphql query but I want to replace this with the user data passed in req / context
        console.log('context', context) // {}
        return await UserService.findOne(email)
    },
};

// Put together a schema
const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
});

如何在解析器中访问我的 JWT 用户数据?

【问题讨论】:

    标签: node.js jwt graphql graphql-js apollo-server


    【解决方案1】:

    显然你需要像这样手动传递上下文:

    app.use('/graphql', [auth_middleware, bodyParser.json()], (req, res) => graphqlExpress({ schema, context: req.user })(req, res) );
    

    如果有人感兴趣,找到答案here

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2016-04-21
      • 2017-06-01
      • 2013-11-23
      • 2022-11-28
      • 1970-01-01
      • 2017-02-05
      • 2018-12-20
      • 2021-08-11
      相关资源
      最近更新 更多