You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJS大JSON对象请求挂起问题求助

NextJS大JSON POST请求挂起问题的解决思路

问题场景

我开发了一个NextJS应用,使用fetch向api/import路由发送POST请求,前端代码如下:

const options = {
  method: "POST",
  headers: {
    Accept: "application/json",
    "Content-Type": "application/json",
  },
  body: JSON.stringify(filesForImport),
};
const response = await fetch("api/import", options);

操作流程简单,但当请求体为约6500行(Postman统计)、大小200KB的大JSON对象时,请求完全挂起:api/import路由未被调用,开发者工具网络面板显示请求处于pending状态且永远无法完成。发送仅20行的小JSON时一切正常,问题出在NextJS对大JSON对象的处理上。

已尝试的方法

我曾尝试修改路由配置关闭默认bodyParser:

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

但并无效果。为测试,我已将路由内所有业务逻辑注释:

export default async (req: NextApiRequest, res: NextApiResponse) => {
  console.log(99999)
  try {
    const files: LocalizationImportData[] = req.body;
    console.log(888, files)
    //await some logic here, which is commented
    res.status(200).end();
  } catch (err: unknown) {
    if (err instanceof Error) console.error(`failed to import records: ${err.stack}`);
    res.status(500).send(err);
  }
};

小负载请求下控制台能打印出99999,但大请求无任何输出。已通过Postman、Edge和Chrome测试,结果一致,请求均永久挂起。

可行的解决办法

1. 调整bodyParser的大小限制

NextJS默认的bodyParser有大小限制,200KB可能刚好触碰到阈值。可以手动设置更大的sizeLimit:

export const config = {
  api: {
    bodyParser: {
      sizeLimit: '500kb', // 根据实际需求调整,比如1MB
    },
  },
};

注意不要直接设置bodyParser: false,而是保留默认解析器并调整参数。

2. 关闭默认bodyParser后手动解析请求体

如果必须关闭默认bodyParser,需要手动读取并解析请求流,否则请求流未被消费会导致连接一直挂起:

import type { NextApiRequest, NextApiResponse } from 'next';

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

export default async (req: NextApiRequest, res: NextApiResponse) => {
  console.log(99999);
  try {
    // 手动读取请求体数据流
    const rawBody = await new Promise<string>((resolve, reject) => {
      let data = '';
      req.on('data', chunk => data += chunk);
      req.on('end', () => resolve(data));
      req.on('error', reject);
    });
    const files: LocalizationImportData[] = JSON.parse(rawBody);
    console.log(888, files);
    res.status(200).end();
  } catch (err: unknown) {
    if (err instanceof Error) console.error(`failed to import records: ${err.stack}`);
    res.status(500).send(err instanceof Error ? err.message : 'Unknown error');
  }
};

3. 升级NextJS到最新稳定版

某些旧版本的NextJS存在大请求体处理的bug,升级到最新版可能解决问题:

npm install next@latest

4. 检查平台/服务器的额外限制

如果部署在Vercel等云平台,需确认平台是否有请求大小限制;如果是自建服务器,检查Node.js或反向代理(如Nginx)的请求大小配置,确保阈值大于200KB。

内容的提问来源于stack exchange,提问作者Eugen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:55:18