首页 > 解决方案 > Next.JS + Apollo Server(bodyParser 问题)

问题描述

在 next.js api 路由函数上使用 apollo 服务器时,我们有:

export const config = {
    api: {
        bodyParser: false
    },
};

这样 Apollo 就不会因 next.js 的请求而失败

但是如果我们删除这个配置,那么我想 Apollo 将无限等待获取未解析的主体(或未解析的请求流)。

在某种情况下,我也得到由(快速服务器或云功能)解析的请求,这将导致 Apollo 挂出并最终因超时错误而失败。

我该如何处理这个问题?

import Cors from 'micro-cors';
import { ApolloServer, gql } from 'apollo-server-micro';

import { NextApiRequest, NextApiResponse } from 'next';

type Todo = {
    ...
};

const todos: Todo[] = [
    ...
];

const todoResolvers = {
    Query: {
        ...
    },

    Mutation: {
        ...
    };

const todoTypes = gql`
    ...
`;




const cors = Cors({
    origin: "*",
    credentials: true,
});

const getApolloServerHandler = async (): Promise<any> => {

    const apolloServer = new ApolloServer({
        typeDefs: [todoTypes],
        resolvers: [todoResolvers],
        introspection: true,
        playground: true,
    });

    const handler = apolloServer.createHandler({  path: '/api/graphql' });
    const corsHandler = cors(handler);
    return corsHandler;
};

export const config = {
    api: {
        bodyParser: false,
    },
};

export default async (req: NextApiRequest, res: NextApiResponse): Promise<void> => {
    const apolloServerHandler = await getApolloServerHandler();
    return apolloServerHandler(req, res);
};

标签: apolloapollo-server

解决方案


推荐阅读