【问题标题】:Apollo Server Express: Request entity too largeApollo Server Express:请求实体太大
【发布时间】:2020-01-25 16:28:51
【问题描述】:

我需要在 GraphQL 突变中发布一个大型有效负载。如何增加 Apollo Server 的 body size 限制?

我使用的是apollo-server-express 2.9.3 版。

我的代码(简化):

const myGraphQLSchema = new GraphQLSchema({
  query: new GraphQLObjectType({
    name: 'Query',
    fields: {
      user: UserQuery,
    },
  }),
  mutation: new GraphQLObjectType({
    name: 'Mutation',
    fields: () => ({
      ...UserMutations,
    }),
  }),
});

const apolloServer = new ApolloServer(schema: myGraphQLSchema);

const app = express();
app.use(apolloServer.getMiddleware({ path: '/graphql' });

【问题讨论】:

    标签: express graphql apollo apollo-server


    【解决方案1】:

    只需在 Apollo 服务器中间件之前添加一个 Express 正文解析器:

    import { json } from 'express';
    
    app.use(json({ limit: '2mb' });
    app.use(apolloServer.getMiddleware({ path: '/graphql' });
    

    如果你想变得花哨,你可以对已验证和未验证的请求设置单独的正文大小限制:

    const jsonParsers = [
      json({ limit: '16kb' }),
      json({ limit: '2mb' }),
    ];
    
    function parseJsonSmart(req: Request, res: Response, next: NextFunction) {
      // How exactly you do auth depends on your app
      const isAuthenticated = req.context.isAuthenticated();
      return jsonParsers[isAuthenticated ? 1 : 0](req, res, next);
    }
    
    app.use(parseJsonSmart);
    app.use(apolloServer.getMiddleware({ path: '/graphql' });
    

    【讨论】:

      【解决方案2】:

      不完全确定它是在哪个版本中添加的,但在 2.9.15 上您可以在 applyMiddleware 函数中应用它。

      const apolloServer = new ApolloServer(someConfig);
      apolloServer.applyMiddleware({
        app,
        cors: {
          origin: true,
          credentials: true,
        },
        bodyParserConfig: {
          limit:"10mb"
        }
      });
      

      【讨论】:

        猜你喜欢
        • 2018-06-10
        • 1970-01-01
        • 2013-03-15
        • 1970-01-01
        • 2016-02-10
        • 2019-03-17
        • 2021-11-12
        • 1970-01-01
        • 2012-02-12
        相关资源
        最近更新 更多