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

Next.js 13中HTTP POST请求无响应问题排查求助

问题分析与解决方案

你的代码在账号不存在时请求会一直挂起,核心问题是缺少全局错误捕获机制,再加上可能存在的环境变量配置错误、bcrypt哈希耗时过长等问题,导致请求无法正常返回响应。以下是具体排查和修复步骤:

1. 全局错误捕获是关键

异步操作(比如Prisma写入、JWT签名)如果抛出错误,当前代码没有任何处理逻辑,会直接导致请求处于pending状态。必须用try/catch包裹整个业务逻辑,捕获错误并返回明确响应:

export async function POST(request: Request) {
  try {
    const { firstName, lastName, email, phone, city, password } = await request.json();
    const errors: string[] = [];

    const validationSchema = [
      {
        valid: validator.isLength(firstName, { min: 1, max: 20 }),
        error: "Invalid first name.",
      },
      {
        valid: validator.isLength(lastName, { min: 1, max: 20 }),
        error: "Invalid last name.",
      },
      {
        valid: validator.isEmail(email),
        error: "Invalid email.",
      },
      {
        valid: validator.isMobilePhone(phone),
        error: "Invalid phone number.",
      },
      {
        valid: validator.isLength(city, { min: 1, max: 20 }),
        error: "Invalid city.",
      },
      {
        valid: validator.isStrongPassword(password),
        error: "Invalid password.",
      },
    ];

    validationSchema.forEach((check) => {
      if (!check.valid) errors.push(check.error);
    });

    if (errors.length) {
      return NextResponse.json(errors[0], { status: 400 });
    }

    const userWithEmail = await prisma.user.findUnique({ where: { email } });
    if (userWithEmail) {
      return NextResponse.json(
        { response: "Your account already exists! Please sign in." },
        { status: 409 }
      );
    }

    // 降低bcrypt哈希轮次,避免耗时过长
    const hash = await bcrypt.hash(password, 12);

    const user = await prisma.user.create({
      data: {
        first_name: firstName,
        last_name: lastName,
        email,
        phone,
        city,
        password: hash,
      },
    });

    const alg = "HS256";
    // 先校验JWT_SECRET是否存在,避免后续报错
    if (!process.env.JWT_SECRET) {
      throw new Error("JWT_SECRET environment variable is not configured");
    }
    const JWTSecret = new TextEncoder().encode(process.env.JWT_SECRET);

    const token = await new jose.SignJWT({ email: user.email })
      .setProtectedHeader({ alg })
      .setExpirationTime("24h")
      .sign(JWTSecret);

    console.log(token);
    return NextResponse.json({ JWT: token }, { status: 201 });
  } catch (error) {
    // 捕获所有错误并返回,避免请求挂起
    console.error("User creation failed:", error);
    return NextResponse.json(
      { error: "Failed to create user" },
      { status: 500 }
    );
  } finally {
    // 确保Prisma连接正常关闭(可选但推荐)
    await prisma.$disconnect();
  }
}

2. 修复核心问题点

  • 降低bcrypt哈希轮次:你设置的22会导致哈希计算耗时极长(bcrypt轮次是指数级增长,22轮计算时间可能超过10秒),直接触发请求超时。改成10-12即可,安全性足够且性能正常。
  • 校验JWT_SECRET环境变量:先检查process.env.JWT_SECRET是否存在,避免TextEncoder.encode(undefined)导致的隐性错误。确保.env文件中正确配置该变量,API路由是服务器端代码,无需加NEXT_PUBLIC_前缀。
  • 添加HTTP状态码:给响应加上明确状态码(如400参数错误、409冲突、201创建成功、500服务器错误),方便调试和前端处理。

3. 调试建议

添加错误捕获后,查看服务器日志(console.error输出),就能直接定位具体错误原因,比如JWT_SECRET未配置、Prisma数据库连接异常等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 01:22:03