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

使用Next.js Server Actions登出重定向报错UND_ERR_REQ_CONTENT_LENGTH_MISMATCH

解决Next.js Server Actions登出重定向时的UND_ERR_REQ_CONTENT_LENGTH_MISMATCH错误

这个错误的核心问题出在Server Action的写法上,结合你的代码,主要有两个需要修正的地方:

1. 修正"use server"的位置

Server Action强制要求"use server"必须是函数体的第一行有效语句,不能有前置的空白行或其他代码。你当前代码里"use server"前面留了空白行,这会让Next.js无法正确识别Server Action的执行边界,进而触发请求内容长度不匹配的错误。

2. 等待异步操作完成

如果authService.logout()是异步函数,你必须用await等待它执行完毕,再进行删除cookie和重定向的操作,否则可能导致逻辑执行不完整就跳转,引发状态不一致。

修复后的完整代码

import { redirect } from "next/navigation";
import { cookies } from 'next/headers'
import { authService } from "@/services";

async function logoutUser() {
  "use server"; // 必须放在函数体第一行,不能有前置空白
  await authService.logout(); // 异步操作加await
  cookies().delete('currentUser');
  redirect('/');
}

export default () => {
  return <>
    <form action={logoutUser} className="flex flex-col gap-3">
      <button className="btn btn-primary normal-case w-full" type="submit">Logout</button>
    </form>
  </>
}

额外验证项

  • 确认你的Next.js版本在v13.4及以上,并且已经在next.config.js中启用Server Actions:
    /** @type {import('next').NextConfig} */
    const nextConfig = {
      experimental: {
        serverActions: true,
      },
    }
    
    module.exports = nextConfig
    
  • 检查authService.logout()的实现,确保它没有额外的响应处理逻辑,避免干扰Server Action的默认流程。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 02:00:06