API 路由支持 [动态路由]](/docs/routing/dynamic-routes.md),并与 pages 一样遵循相同的文件命名规则。
例如,API 路由 pages/api/post/[pid].js 的实现代码如下:
export default function handler(req, res) {
const { pid } = req.query
res.end(`Post: ${pid}`)
}
现在,发往 /api/post/abc 的请求将收到响应: Post: abc。
一个通常的 RESTful 模式将设置以下路由:
GET api/posts - 获取 post 列表,可能还有分页GET api/posts/12345 - 获取 id 为 12345 的 post我们可以按照如下两种方式建模:
/api/posts.js/api/posts/[postId].js/api/posts/index.js/api/posts/[postId].js以上两种方案是等效的。还有一个仅使用 /api/posts/[postId].js 的第三种方式,由于动态路由 (including Catch-all routes - see below) 没有 undefined 状态,而 GET api/posts 在任何情况下都不匹配 /api/posts/[postId].js,因此这种方式是无效的。
通过在方括号内添加三个英文句点 (...) 即可将 API 路由扩展为能够捕获所有路径的路由。例如:
pages/api/post/[...slug].js 匹配 /api/post/a,也匹配 /api/post/a/b、/api/post/a/b/c 等。注意:
slug并不是必须使用的,你也可以使用[...param]
匹配的参数将作为查询参数(本例中的 slug )传递给 page(页面),并且始终是数组格式,因此,路经 /api/post/a 将拥有以下query 对象:
{ "slug": ["a"] }
对于 /api/post/a/b 路径,以及任何其他匹配的路径,新参数将被添加到数组中,如下所示:
{ "slug": ["a", "b"] }
API 路由 pages/api/post/[...slug].js 将是如下所示:
export default function handler(req, res) {
const { slug } = req.query
res.end(`Post: ${slug.join(', ')}`)
}
现在,一个发送到 /api/post/a/b/c 的请求将收到 Post: a, b, c 响应。
通过将参数放在双方括号中 ([[...slug]]) 可以使所有路径成为可选路径。
例如, pages/api/post/[[...slug]].js 将匹配 /api/post、/api/post/a、/api/post/a/b 等。
The main difference between catch all and optional catch all routes is that with optional, the route without the parameter is also matched (/api/post in the example above).
该 query 对象如下所示:
{ } // GET `/api/post` (empty object)
{ "slug": ["a"] } // `GET /api/post/a` (single-element array)
{ "slug": ["a", "b"] } // `GET /api/post/a/b` (multi-element array)
pages/api/post/create.js - 将匹配 /api/post/createpages/api/post/[pid].js - 将匹配 /api/post/1, /api/post/abc 等,但不匹配 /api/post/createpages/api/post/[...slug].js - 将匹配 /api/post/1/2, /api/post/a/b/c 等,但不匹配 /api/post/create、/api/post/abcFor more information on what to do next, we recommend the following sections: