如果说 Server Component 像后厨,Server Action 像内部办公流转,
那 route.ts 更像 对外服务窗口。
// app/api/products/route.ts
export async function GET() {
const products = [
{ id: 'p1', name: '键盘' },
{ id: 'p2', name: '显示器' },
];
return Response.json(products);
}// app/api/products/route.ts
export async function POST(request: Request) {
const body = await request.json();
return Response.json({
ok: true,
received: body,
});
}#什么时候该用 Route Handler
- 你要暴露 JSON API 给浏览器、移动端、第三方系统
- 你要返回文件、文本、Webhook 响应
- 你要做真正的 HTTP 接口边界
#什么时候不该滥用它
- 你已经在 Server Component 里
- 你只是想给本页首屏拿数据
- 你只是要在服务端内部调数据库
一句话判断:
给“外部 HTTP 世界”用 → route.ts
给“当前页面/当前服务端树”用 → 直接调函数、调数据库、调内部服务