下面给你一个实用且较为复杂的 Next.js API 路由示例,涵盖了常见的功能点:
-
支持 GET、POST 请求
-
简单的参数校验
-
返回分页数据
-
异步数据库模拟操作(用内存模拟,便于理解)
-
统一错误处理
-
CORS 支持
// pages/api/items.ts
import type { NextApiRequest, NextApiResponse } from 'next'
// 模拟数据库
let items = Array.from({ length: 50 }, (_, i) => ({
id: i + 1,
name: `Item ${i + 1}`,
description: `This is the description for item ${i + 1}`
}))
type Item = {
id: number
name: string
description: string
}
type Data =
| { success: true; data: Item[]; total: number }
| { success: false; error: string }
| { success: true; data: Item }
export default async function handler(req: NextApiRequest, res: NextApiResponse<Data>)

订阅专栏 解锁全文
1254

被折叠的 条评论
为什么被折叠?



