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

如何在NextJS(含NodeJS)API路由中无需插件代理传递multipart/form-data

NextJS API路由无插件代理multipart/form-data方案

第一步:关闭API路由内置body解析

NextJS默认会自动解析所有传入请求的body,要保留multipart原始数据,必须先禁用该行为。在对应API路由文件中导出如下配置:

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

第二步:读取原始请求二进制数据

无需借助第三方解析库,直接通过Node.js原生的req流读取完整的原始body缓冲区即可:

// 小文件场景:先读取完整body再转发
const rawBody = await new Promise((resolve, reject) => {
  const chunks = [];
  req.on('data', (chunk) => chunks.push(chunk));
  req.on('end', () => resolve(Buffer.concat(chunks)));
  req.on('error', reject);
});

第三步:转发请求到目标服务

转发时必须原样携带原始请求的content-type头(包含multipart的边界标识),其他头和参数可按需调整,完整示例代码如下:

import http from 'http';
import https from 'https';

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

export default async function handler(req, res) {
  // 替换为实际目标服务配置
  const TARGET_HOST = 'your-target-service.com';
  const IS_TARGET_HTTPS = true;
  const TARGET_PATH = req.url;

  const requestOptions = {
    host: TARGET_HOST,
    port: IS_TARGET_HTTPS ? 443 : 80,
    path: TARGET_PATH,
    method: req.method,
    headers: {
      ...req.headers,
      host: TARGET_HOST,
      // 必须原样保留content-type,里面的boundary是form-data解析的核心参数
      'content-type': req.headers['content-type'],
    },
  };

  const client = IS_TARGET_HTTPS ? https : http;
  const proxyReq = client.request(requestOptions, (proxyRes) => {
    res.writeHead(proxyRes.statusCode, proxyRes.headers);
    proxyRes.pipe(res, { end: true });
  });

  proxyReq.on('error', (err) => {
    res.status(500).json({ error: '代理请求失败', details: err.message });
  });

  // 写入原始body并发送请求
  proxyReq.write(rawBody);
  proxyReq.end();
}

注意事项

  • 必须保留原始请求的content-type头,里面包含的boundary参数是目标服务解析multipart/form-data的核心标识,丢失会导致目标服务无法识别请求格式
  • 如果需要过滤请求头,不要过滤content-type和content-length字段
  • 大文件上传场景下可以优化为流转发,不需要先把整个body读入内存,直接把req流pipe到proxyReq即可,内存占用更低:
// 大文件场景直接替换读取rawBody和写入逻辑即可
req.pipe(proxyReq);

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 05:45:08