Apollo Server Express:请求实体太大 [英] Apollo Server Express: Request entity too large
本文介绍了Apollo Server Express:请求实体太大的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在 GraphQL 突变中发布一个大型负载.如何增加 Apollo Server 的 body 大小限制?
I need to POST a large payload in a GraphQL mutation. How do I increase the body size limit of Apollo Server?
我使用的是 apollo-server-express
版本 2.9.3.
I'm using apollo-server-express
version 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' });
推荐答案
只需在 Apollo 服务器中间件之前添加一个 Express 正文解析器:
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' });
这篇关于Apollo Server Express:请求实体太大的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文