Apollo Server Express: Request entity too large

风格不统一 提交于 2021-02-10 14:25:48

问题


I need to POST a large payload in a GraphQL mutation. How do I increase the body size limit of Apollo Server?

I'm using apollo-server-express version 2.9.3.

My code (simplified):

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' });

回答1:


Simply add an Express body parser before your Apollo server middleware:

import { json } from 'express';

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

If you want to get fancy, you can have a separate body size limit for authenticated vs unauthenticated requests:

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:


Not exactly sure in which version it was added, but on 2.9.15 you can apply it in applyMiddleware function.

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


来源:https://stackoverflow.com/questions/58099083/apollo-server-express-request-entity-too-large

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!