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

Next.js集成next-auth保护API时请求长度不匹配问题求助

解决Next.js中fetch请求的RequestContentLengthMismatchError错误

问题原因

直接将headers()返回的所有请求头传递给新的fetch请求,会触发两个核心问题:

  1. 原请求的Content-Length头被带入新请求,但新请求的body内容(空字符串)长度和该值不匹配,触发长度校验错误。
  2. 原请求中的部分头(如Host、Connection)不适合在客户端fetch请求中发送,可能引发额外异常。

解决方案

不要全盘传递headers(),而是只提取认证所需的头信息,再根据实际请求的body类型手动设置必要的头,避免手动设置Content-Length(让浏览器自动处理更可靠)。

修改后的代码示例

场景1:传递FormData(推荐,自动处理Content-Type和长度)

// /lib/getData.ts
import { headers } from "next/headers";

export default async function addData(data: FormData) {
    try {
        const requestHeaders = headers();
        const fetchHeaders = new Headers();
        
        // 提取next-auth会话所需的Cookie头
        const cookie = requestHeaders.get('Cookie');
        if (cookie) {
            fetchHeaders.set('Cookie', cookie);
        }

        await fetch('/api/data', {
            method: "POST",
            headers: fetchHeaders,
            body: data // 传递实际的FormData,浏览器自动处理Content-Type和Content-Length
        });
    } catch(error) {
        console.error(error);
    }

    return null;
}

场景2:传递空body

// /lib/getData.ts
import { headers } from "next/headers";

export default async function addData(data: FormData) {
    try {
        const requestHeaders = headers();
        
        await fetch('/api/data', {
            method: "POST",
            headers: {
                // 仅传递认证Cookie
                'Cookie': requestHeaders.get('Cookie') || '',
                // 为空body设置合适的Content-Type
                'Content-Type': 'text/plain'
            },
            body: ""
        });
    } catch(error) {
        console.error(error);
    }

    return null;
}

补充说明

  • Next-Auth在服务端通过Cookie识别会话,所以只需传递Cookie头即可完成认证,无需传递所有请求头。
  • 如果发送JSON格式的body,需手动设置Content-Type: application/json,并将body转为JSON字符串,浏览器会自动计算并设置Content-Length。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 11:52:46