【问题标题】:How to pass arguments to graphqlHTTP middleware如何将参数传递给 graphqlHTTP 中间件
【发布时间】:2026-01-03 10:30:01
【问题描述】:

如何将参数传递给 graphqlHTTP 中间件

我正在尝试将授权标头令牌有效负载从另一个上层中间件传递给 graphqlHTTP 中间件

app.use('/private', (req:Request,res:Response,next:Function) => {

   if(!req.header('Authorization')){
      res.json({
         error:true,
         message:'Authorization bearer required'
      })
   }else{
      const token = Buffer.from(req.header('Authorization').split('Bearer ')[1], 'base64').toString('ascii');
      if(decode(token)){
         next();
      }else{
         res.json({
            error:true,
            message:'Authorization bearer required'
         })
      }
   }
});

app.use('/private', graphqlHTTP({
   schema:privateSchema,
   graphiql:false
}))

【问题讨论】:

    标签: node.js express graphql-js


    【解决方案1】:

    从请求本身的中间件中设置数据是很常见的。

    在您的场景中,令牌可以设置为req.token,然后传递给您的 graphql 解析器上下文,例如:

    // main.js
    
    app.use(authMidddleware) // sets req.token
    app.use(
      '/graphql',
      bodyParser.json(),
      graphqlExpress(req => ({ schema, context: req }))
    )
    
    // some-resolver.js
    export const myResolver = {
      Query: {
        token: async (parent, { input }, context) => {
          const { token } = context;
          // other stuff
        }
      }
    }
    

    【讨论】:

      【解决方案2】:

      最近试过了,效果不错:

      jwtAuth - 检查授权标头以获取令牌的中间件。 对其进行解码并将凭据存储在 req.auth 中。

      文件映射

      ...
      [graphql]
      [utils]
      index.js
      

      index.js

      ...

      const graphqlSettings = require("./graphql/settings");
      const jwtAuth = require("./utils/jwtAuth");
      // init
      ...
      // parser
      ...
      // cors setup
      ...        
      // JWT authentication
      app.use(jwtAuth);    
      // graphql init
      app.use("/graphql", graphqlSettings);
      ...
      

      settings.js

      ...
      const { graphqlHTTP } = require("express-graphql");
      const typeDefs = require("./typeDefs");
      const resolvers = require("./resolvers");
      // models
      ...
      // extend context with models
      const models = {
          ...
      };
      
      module.exports = graphqlHTTP((req) => ({
          graphiql: true,
          schema: typeDefs,
          rootValue: resolvers,
          context: {
              ...models,
              auth: req.auth,
          },
      }));
      

      【讨论】:

        最近更新 更多