NNext.js 中文网 GitHub

API 路由

Next.js 支持 API 路由,让你可以直接在 Next.js 应用中构建 API。在此了解其工作原理。

<details> <summary>示例</summary>

</details>

小知识:如果你使用的是 App Router,可以使用 Server Components 或 Route Handlers 来代替 API 路由。

API 路由提供了一种使用 Next.js 构建公共 API 的解决方案。

pages/api 文件夹中的任何文件都会被映射到 /api/*,并被视为 API 端点而不是 page。它们只在服务端打包,不会增加客户端的打包体积。

例如,下面的 API 路由返回一个状态码为 200 的 JSON 响应:

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

type ResponseData = {
  message: string
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.status(200).json({ message: 'Hello from Next.js!' })
}
pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from Next.js!' })
}

小知识:

参数#

tsx
export default function handler(req: NextApiRequest, res: NextApiResponse) {
  // ...
}

HTTP 方法#

要在 API 路由中处理不同的 HTTP 方法,你可以在请求处理程序中使用 req.method,如下所示:

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  if (req.method === 'POST') {
    // 处理 POST 请求
  } else {
    // 处理其他任何 HTTP 方法
  }
}
pages/api/hello.js
export default function handler(req, res) {
  if (req.method === 'POST') {
    // 处理 POST 请求
  } else {
    // 处理其他任何 HTTP 方法
  }
}

请求辅助函数#

API 路由提供内置的请求辅助函数来解析传入的请求(req):

  • req.cookies - 包含请求发送的 cookie 的对象。默认为 {}
  • req.query - 包含查询字符串的对象。默认为 {}
  • req.body - 包含由 content-type 解析的请求体的对象,如果没有发送请求体则为 null

自定义配置#

每个 API 路由都可以导出一个 config 对象来更改默认配置,默认配置如下:

js
export const config = {
  api: {
    bodyParser: {
      sizeLimit: '1mb',
    },
  },
  // 指定此函数允许执行的最长时间(以秒为单位)
  maxDuration: 5,
}

bodyParser 会自动启用。如果你希望以 Stream 或使用 raw-body 的方式读取请求体,可以将其设置为 false。

禁用自动 bodyParser 的一个用例是让你能够验证 webhook 请求的原始请求体,例如来自 GitHub 的请求。

js
export const config = {
  api: {
    bodyParser: false,
  },
}

bodyParser.sizeLimit 是解析后的请求体允许的最大大小,可以是 bytes 支持的任何格式,如下所示:

js
export const config = {
  api: {
    bodyParser: {
      sizeLimit: '500kb',
    },
  },
}

externalResolver 是一个显式标志,用于告知服务器此路由由外部解析器(如 express 或 connect)处理。启用此选项会禁用未解析请求的警告。

js
export const config = {
  api: {
    externalResolver: true,
  },
}

responseLimit 会自动启用,当 API 路由的响应体超过 4MB 时发出警告。

如果你不是在 serverless 环境中使用 Next.js,并且了解不使用 CDN 或专用媒体主机对性能的影响,可以将此限制设置为 false。

js
export const config = {
  api: {
    responseLimit: false,
  },
}

responseLimit 也可以接受字节数或 bytes 支持的任何字符串格式,例如 1000、'500kb' 或 '3mb'。 该值为显示警告前的最大响应大小。默认值为 4MB。(见上文)

js
export const config = {
  api: {
    responseLimit: '8mb',
  },
}

响应辅助函数#

Server Response 对象(通常缩写为 res)包含一组类似 Express.js 的辅助方法,用于改善开发者体验并提高创建新 API 端点的速度。

包含的辅助方法如下:

  • res.status(code) - 用于设置状态码的函数。code 必须是有效的HTTP 状态码
  • res.json(body) - 发送 JSON 响应。body 必须是可序列化对象
  • res.send(body) - 发送 HTTP 响应。body 可以是 string、object 或 Buffer
  • res.redirect([status,] path) - 重定向到指定路径或 URL。status 必须是有效的HTTP 状态码。如果未指定,status 默认为 "307"("Temporary redirect",临时重定向)。
  • res.revalidate(urlPath) - 使用 getStaticProps 按需重新验证页面。urlPath 必须是 string。

设置响应的状态码#

向客户端发送响应时,你可以设置响应的状态码。

以下示例将响应的状态码设置为 200(OK),并返回一个值为 Hello from Next.js! 的 message 属性作为 JSON 响应:

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

type ResponseData = {
  message: string
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.status(200).json({ message: 'Hello from Next.js!' })
}
pages/api/hello.js
export default function handler(req, res) {
  res.status(200).json({ message: 'Hello from Next.js!' })
}

发送 JSON 响应#

向客户端发送响应时,你可以发送 JSON 响应,它必须是可序列化对象。 在真实世界的应用中,你可能希望根据所请求端点的结果让客户端知道请求的状态。

以下示例发送一个状态码为 200(OK)且包含异步操作结果的 JSON 响应。该示例包含在 try catch 块中,以处理可能发生的任何错误,并捕获相应的状态码和错误消息发送回客户端:

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    const result = await someAsyncOperation()
    res.status(200).json({ result })
  } catch (err) {
    res.status(500).json({ error: 'failed to load data' })
  }
}
pages/api/hello.js
export default async function handler(req, res) {
  try {
    const result = await someAsyncOperation()
    res.status(200).json({ result })
  } catch (err) {
    res.status(500).json({ error: 'failed to load data' })
  }
}

发送 HTTP 响应#

发送 HTTP 响应的方式与发送 JSON 响应相同。唯一的区别是响应体可以是 string、object 或 Buffer。

以下示例发送一个状态码为 200(OK)且包含异步操作结果的 HTTP 响应。

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  try {
    const result = await someAsyncOperation()
    res.status(200).send({ result })
  } catch (err) {
    res.status(500).send({ error: 'failed to fetch data' })
  }
}
pages/api/hello.js
export default async function handler(req, res) {
  try {
    const result = await someAsyncOperation()
    res.status(200).send({ result })
  } catch (err) {
    res.status(500).send({ error: 'failed to fetch data' })
  }
}

重定向到指定路径或 URL#

以表单为例,你可能希望在客户端提交表单后将其重定向到指定路径或 URL。

以下示例在表单成功提交后将客户端重定向到 / 路径:

pages/api/hello.ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const { name, message } = req.body

  try {
    await handleFormInputAsync({ name, message })
    res.redirect(307, '/')
  } catch (err) {
    res.status(500).send({ error: 'Failed to fetch data' })
  }
}
pages/api/hello.js
export default async function handler(req, res) {
  const { name, message } = req.body

  try {
    await handleFormInputAsync({ name, message })
    res.redirect(307, '/')
  } catch (err) {
    res.status(500).send({ error: 'failed to fetch data' })
  }
}

添加 TypeScript 类型#

你可以通过从 next 导入 NextApiRequest 和 NextApiResponse 类型来使 API 路由更加类型安全,除此之外,你还可以为响应数据定义类型:

ts
import type { NextApiRequest, NextApiResponse } from 'next'

type ResponseData = {
  message: string
}

export default function handler(
  req: NextApiRequest,
  res: NextApiResponse<ResponseData>
) {
  res.status(200).json({ message: 'Hello from Next.js!' })
}

小知识:NextApiRequest 的 body 是 any 类型,因为客户端可能包含任何有效载荷。你应该在使用前于运行时验证 body 的类型/结构。

动态 API 路由#

API 路由支持动态路由,并遵循与 pages/ 相同的文件命名规则。

pages/api/post/[pid].ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const { pid } = req.query
  res.end(`Post: ${pid}`)
}
pages/api/post/[pid].js
export default function handler(req, res) {
  const { pid } = req.query
  res.end(`Post: ${pid}`)
}

现在,对 /api/post/abc 的请求将返回文本:Post: abc。

捕获所有 API 路由#

API 路由可以通过在方括号内添加三个点(...)来扩展为捕获所有路径。例如:

  • pages/api/post/[...slug].js 匹配 /api/post/a,也匹配 /api/post/a/b、/api/post/a/b/c 等。

小知识:你可以使用 slug 以外的名称,例如:[...param]

匹配的参数会作为查询参数(示例中为 slug)发送到页面,并且它始终是一个数组,因此路径 /api/post/a 将具有以下 query 对象:

json
{ "slug": ["a"] }

对于 /api/post/a/b 以及任何其他匹配的路径,新参数会被添加到数组中,如下所示:

json
{ "slug": ["a", "b"] }

例如:

pages/api/post/[...slug].ts
import type { NextApiRequest, NextApiResponse } from 'next'

export default function handler(req: NextApiRequest, res: NextApiResponse) {
  const { slug } = req.query
  res.end(`Post: ${slug.join(', ')}`)
}
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 等。

捕获所有路由与可选的捕获所有路由的主要区别在于,可选路由还会匹配不带参数的路由(上例中的 /api/post)。

query 对象如下:

json
{ } // GET `/api/post`(空对象)
{ "slug": ["a"] } // `GET /api/post/a`(单元素数组)
{ "slug": ["a", "b"] } // `GET /api/post/a/b`(多元素数组)

注意事项#

  • 预定义的 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

流式响应#

虽然 Pages Router 确实支持通过 API 路由进行流式响应,但如果你使用的是 Next.js 14 或更高版本,我们建议逐步采用 App Router 并使用 Route Handlers。

以下是如何使用 writeHead 从 API 路由流式传输响应:

pages/api/hello.ts
import { NextApiRequest, NextApiResponse } from 'next'

export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse
) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-store',
  })
  let i = 0
  while (i < 10) {
    res.write(`data: ${i}\n\n`)
    i++
    await new Promise((resolve) => setTimeout(resolve, 1000))
  }
  res.end()
}
pages/api/hello.js
export default async function handler(req, res) {
  res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-store',
  })
  let i = 0
  while (i < 10) {
    res.write(`data: ${i}\n\n`)
    i++
    await new Promise((resolve) => setTimeout(resolve, 1000))
  }
  res.end()
}
Next.js 中文网