Next.js 13 App Router API路由出现404错误求助
路径参数路由结构错误
你的API路由文件放在app/api/draw-cards/route.ts,这个路径仅能匹配/api/draw-cards的请求,但你调用的是/api/draw-cards/${deck_id}(带路径参数)的格式。在Next.js 13 App Router中,要支持路径参数,需要创建[deck_id]子文件夹,正确的文件路径应为app/api/draw-cards/[deck_id]/route.ts,这样才能匹配/api/draw-cards/xxx格式的请求。服务函数参数类型错误导致路径拼接异常
你的drawCards函数参数类型定义存在问题:interface DrawCardsProps { deck_id: string; } export async function drawCards(deck_id: DrawCardsProps) {参数
deck_id的类型被定义为DrawCardsProps(对象类型),但拼接URL时直接使用了deck_id。如果调用时传入的是{ deck_id: "xxx" },最终拼接的路径会变成/api/draw-cards/[object Object],这个不存在的路径自然返回404。正确的做法有两种:- 修改参数类型为字符串:
export async function drawCards(deck_id: string) { - 解构对象获取
deck_id:export async function drawCards({ deck_id }: DrawCardsProps) { const response = await fetch(`/api/draw-cards/${deck_id}`, { method: "GET" }); }
- 修改参数类型为字符串:
App Router API路由误用Pages Router类型和参数获取方式
你在API路由里导入了NextApiRequest(属于Pages Router的类型),但App Router的API路由应使用NextRequest,并且路径参数需要通过params对象获取,而非req.query。如果修正了路由结构到[deck_id]/route.ts,正确的API路由代码示例如下:import { NextRequest, NextResponse } from "next/server"; import { z } from "zod"; export async function GET(request: NextRequest, { params }: { params: { deck_id: string } }) { const querySchema = z.string(); const deck = querySchema.parse(params.deck_id); try { const shuffledDeck = await fetch(`https://deckofcardsapi.com/api/deck/${deck}/draw/?count=2`); if (shuffledDeck.ok) { const data = await shuffledDeck.json(); return NextResponse.json(data); } else { return NextResponse.json({ message: "Failed Getting Deck" }, { status: shuffledDeck.status }); } } catch (err) { return NextResponse.json({ message: "Internal server error" }, { status: 500 }); } }另外需要注意:你之前直接返回
NextResponse.json(shuffledDeck)是错误的,因为shuffledDeck是Response对象,需要先解析为JSON再返回。
内容的提问来源于stack exchange,提问作者Zack Amin

