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

Next.js结合PostgreSQL用Route Handler遇POST请求404问题

Next.js POST路由返回404的解决方案

核心问题:路由语法与目录不匹配

你的pages/api/create.js使用了App Router的NextResponse和export async function POST(request)语法,但文件放在了Pages Router专属的pages/api目录下,两种路由系统不兼容,直接导致404错误。

方案1:适配Pages Router(保留当前文件位置)

修改pages/api/create.js为Pages Router的API路由格式,使用req/res对象而非NextResponse:

import { query } from "../../lib/db";

export default async function handler(req, res) {
  // 限制仅POST请求访问
  if (req.method !== "POST") {
    return res.status(405).json({ error: "Method not allowed" });
  }

  try {
    const { contact_name, area_code, phone_number, email, address } = req.body;

    // 修复SQL占位符数量不匹配问题
    const result = await query(
      "INSERT INTO phonebook (contact_name, area_code, phone_number, email, address) VALUES ($1, $2, $3, $4, $5) RETURNING *",
      [contact_name, area_code, phone_number, email, address]
    );

    res.status(201).json({
      message: "Contact added successfully",
      contact: result.rows[0],
    });
  } catch (error) {
    console.error("Error inserting data into phonebook:", error);
    res.status(500).json({
      error: "Failed to add contact",
      details: error.message,
    });
  }
}

方案2:迁移到App Router(若项目基于App Router)

如果你的项目使用App Router(存在app目录),将API路由移至app/api/create/route.js,保留原NextResponse写法,同时修复SQL占位符:

import { NextResponse } from "next/server";
import { query } from "@/lib/db"; // 路径适配App Router

export async function POST(request) {
  try {
    const { contact_name, area_code, phone_number, email, address } =
      await request.json();

    const result = await query(
      "INSERT INTO phonebook (contact_name, area_code, phone_number, email, address) VALUES ($1, $2, $3, $4, $5) RETURNING *",
      [contact_name, area_code, phone_number, email, address]
    );

    return NextResponse.json(
      {
        message: "Contact added successfully",
        contact: result.rows[0],
      },
      { status: 201 }
    );
  } catch (error) {
    console.error("Error inserting data into phonebook:", error);
    return NextResponse.json(
      {
        error: "Failed to add contact",
        details: error.message,
      },
      { status: 500 }
    );
  }
}

额外修复项

  1. SQL语句错误:原代码VALUES ($1, $2)仅定义2个占位符,但传入5个参数,会触发数据库报错,需补全为VALUES ($1, $2, $3, $4, $5)。
  2. 前端表单错误提示:
    • contact_name字段的错误提示引用了errors.contactName(驼峰命名),需改为errors.contact_name?.message(匹配字段下划线命名);
    • email和address的必填提示文案错误,应分别改为"Email is required"和"Address is required"。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 03:16:10