Graphql Can';t在apollo server中将上下文设置为解析器

Graphql Can';t在apollo server中将上下文设置为解析器,graphql,apollo,graphql-js,apollo-server,graphql-modules,Graphql,Apollo,Graphql Js,Apollo Server,Graphql Modules,你好,我是GraphQl和Apollo服务器的新手。 我想在我的项目上实现身份验证 但是 由于某些原因,我似乎无法在apollo server中设置解析程序的上下文 这是我的索引 const server = new ApolloServer({ typeDefs, resolvers, context: ({ req }) => { const userId = jwtDecode(req.headers

你好,我是GraphQl和Apollo服务器的新手。 我想在我的项目上实现身份验证

但是

由于某些原因,我似乎无法在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',
........


上下文
函数中返回的内容应始终是对象。所以你会这样做

context: ({ req }) => {
  const { sub } = jwtDecode(req.headers.authorization)
  return {
    sub,
  }
}
然后通过调用
context.sub
访问解析器中的值


但是,如果您正在使用GraphQL模块创建模式,则应遵循库中的说明,以便在每个模块的基础上配置上下文。

您可以将代码添加到
jwtDecode
方法吗?您好!我只是在NPM上使用jwt解码模块,
userId
有什么作用?你能记录它并检查它打印的内容吗?我认为您正在解码的
req.headers.authorization
(令牌)可能有问题。这是解码的令牌{iss:'',sub:'wNfr5wYesnNYSUGObOP6l64FzdMrSulB@clients“,aud:”,iat:158431388,exp:158437788,azp:'Wnfr5Wyesnnysugobip6l64fzdmrsulb',作用域:'read:client_grants….试图为上下文返回字符串,仍然是相同的错误。非常感谢!!!问题是因为graphql模块,将定义读取文档的内容!”N