【问题标题】:Can't set context to resolvers in apollo server无法为阿波罗服务器中的解析器设置上下文
【发布时间】:2020-06-27 12:17:40
【问题描述】:

您好,我是 GraphQl 和 Apollo Server 的新手。 我想对我的项目实施身份验证。

但是

由于某种原因,我似乎无法在阿波罗服务器中的解析器上设置上下文。

这是我的索引

    const server = new ApolloServer({ 
        typeDefs, 
        resolvers, 
        context: ({ req }) => {
           const userId = jwtDecode(req.headers.authorization)
           return userId.sub
        }
    })

还有我的查询

    Query: {
        users: async (parent, args, context) => {
            try {
                console.log(context)
                return await getUsers(context)
            } catch (err) {
                console.log(err)
                throw new Error(err.message)
            }
        }

When I try to output the context the result is always like this...


{ injector:
   Injector {
     options:
      { name: 'index.ts_8346047369535445_SESSION',
        injectorScope: 'SESSION',
        hooks: [Array],
        children: [] },
     _classMap: Map {},
     _factoryMap: Map {},
     _applicationScopeInstanceMap:
      Map {
        Symbol(ModuleConfig.index.ts_8346047369535445) => undefined,
        [Function] => undefined },
     _sessionScopeInstanceMap: Map { [Function: ModuleSessionInfo] => [ModuleSessionInfo] },
     _applicationScopeServiceIdentifiers:
      [ Symbol(ModuleConfig.index.ts_8346047369535445), [Function] ],
     _requestScopeServiceIdentifiers: [],
     _sessionScopeServiceIdentifiers: [ [Function: ModuleSessionInfo] ],
     _hookServiceIdentifiersMap: Map {},
     _name: 'index.ts_8346047369535445_SESSION',
     _injectorScope: 'SESSION',
     _defaultProviderScope: 'SESSION',
........

【问题讨论】:

  • 可以在jwtDecode方法中添加代码吗?
  • 您好!我只是在 npm 上使用 jwt-decode 模块
  • userId 持有什么?你可以控制台记录它并检查它打印的内容吗?我认为您正在解码的req.headers.authorization(令牌)可能有问题。
  • 这是解码后的令牌 { iss: 'test-api.auth0.com', sub: 'wNfr5wYesnNYSUGObOP6l64FzdMrSulB@clients', aud: 'test-api.auth0.com/api/v2', iat: 1584351388, exp: 15844378, azp:78 'wNfr5wYesnNYSUGObOP6l64FzdMrSulB',范围:'read:client_grants....
  • 试图返回一个字符串作为上下文,仍然是同样的错误。

标签: graphql apollo graphql-js apollo-server graphql-modules


【解决方案1】:

context 函数中返回的内容应该始终是一个对象。所以你会做类似的事情

context: ({ req }) => {
  const { sub } = jwtDecode(req.headers.authorization)
  return {
    sub,
  }
}

然后通过调用context.sub 访问解析器中的值。

但是,如果您使用 GraphQL 模块来创建架构,则应遵循库的 documentation 以基于每个模块配置上下文。

【讨论】:

  • 非常感谢!!!问题是由于 graphql 模块,将 def 阅读文档
猜你喜欢
  • 2021-09-09
  • 2021-04-29
  • 2019-09-15
  • 2019-10-08
  • 2019-02-08
  • 2020-01-14
  • 2019-03-06
  • 1970-01-01
  • 2018-09-09
相关资源
最近更新 更多