# 动态 API 路由

示例

  • 基本 API 路由

API 路由支持 动态路由],并与 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

# 索引路由(Index routes)和动态 API 路由

一个通常的 RESTful 模式将设置以下路由:

  • GET api/posts- 获取 post 列表,可能还有分页
  • GET api/posts/12345- 获取 id 为 12345 的 post

我们可以按照如下两种方式建模:

  • 方案 1:

  • /api/posts.js

  • /api/posts/[postId].js

  • 方案 2:

  • /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 的路由

通过在方括号内添加三个英文句点 (...) 即可将 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响应。

# 可选的捕获所有 API 的路由

通过将参数放在双方括号中 ([[...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/postin 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)

# 注意事项

  • 预定义的 API 路由优先于动态 API 路由,而动态 API 路由优先于捕获所有 API 的路由。看下面的例子:
  • pages/api/post/create.js- 将匹配 /api/post/create
  • pages/api/post/[pid].js- 将匹配 /api/post/1, /api/post/abc等,但不匹配 /api/post/create
  • pages/api/post/[...slug].js- 将匹配 /api/post/1/2, /api/post/a/b/c等,但不匹配 /api/post/create/api/post/abc

# 相关内容

For more information on what to do next, we recommend the following sections:

动态路由:了解有关内置动态路由的更多信息。

Last Updated: 5/13/2023, 8:55:38 PM