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

Next.js同路由如何处理ID与标题两种DELETE请求?

解决方案:Next.js中支持通过ID或标题删除资源的路由处理

核心思路

Next.js不允许在同一层级创建多个同名的动态路由文件夹,所以需要将两种删除逻辑合并到同一个动态路由处理程序中,通过判断传入参数的类型或格式来区分是ID还是标题。

推荐方案:使用单个动态段(如[identifier])替代[reminderId]

这种方案更简洁,语义更清晰,适合仅需要单个动态参数的场景:

  1. 修改文件结构:将原有的api/reminders/[reminderId]文件夹重命名为api/reminders/[identifier]。
  2. 更新处理逻辑:在该文件夹下的route.ts(或index.ts,取决于Next.js版本)中,判断传入的identifier是ID还是标题,再执行对应的删除逻辑:
// app/api/reminders/[identifier]/route.ts
import { NextResponse } from 'next/server';

export async function DELETE(request: Request, { params }: { params: { identifier: string } }) {
  const { identifier } = params;

  // 假设ID是数字类型,先尝试按ID删除
  if (!isNaN(Number(identifier))) {
    const reminderId = parseInt(identifier, 10);
    // 此处替换为你的按ID删除数据库逻辑
    // const deleted = await db.reminder.delete({ where: { id: reminderId } });
    
    return NextResponse.json({ 
      message: `提醒已通过ID ${reminderId} 删除` 
    });
  }

  // 非数字则按标题删除
  const reminderTitle = identifier;
  // 此处替换为你的按标题删除数据库逻辑
  // const deleted = await db.reminder.delete({ where: { title: reminderTitle } });

  return NextResponse.json({ 
    message: `提醒已通过标题 "${reminderTitle}" 删除` 
  });
}

备选方案:使用[...params]捕获所有参数

这种方案适合未来可能需要扩展多参数的场景,但对于当前需求略显冗余:

  1. 创建路由文件:在api/reminders目录下创建[...params]/route.ts文件(替换原有的[reminderId]文件夹)。
  2. 处理参数逻辑:从params数组中提取第一个元素作为标识符,再执行判断:
// app/api/reminders/[...params]/route.ts
import { NextResponse } from 'next/server';

export async function DELETE(request: Request, { params }: { params: { params: string[] } }) {
  const [identifier] = params.params;

  if (!identifier) {
    return NextResponse.json(
      { error: '必须提供ID或标题' }, 
      { status: 400 }
    );
  }

  // 同上述判断逻辑
  if (!isNaN(Number(identifier))) {
    const reminderId = parseInt(identifier, 10);
    // 按ID删除逻辑
    return NextResponse.json({ message: `提醒已通过ID ${reminderId} 删除` });
  }

  const reminderTitle = identifier;
  // 按标题删除逻辑
  return NextResponse.json({ message: `提醒已通过标题 "${reminderTitle}" 删除` });
}

注意事项

  • 冲突处理:如果存在标题为数字且与某个ID重复的情况,需要明确优先级(比如优先按ID处理),或在业务层保证标题不会与ID格式冲突。
  • 路由优先级:确保[identifier]或[...params]路由不会与其他静态路由冲突(比如如果有api/reminders/all这样的静态路由,动态路由不会覆盖它)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:22:42