Guide

获取


¥Fetch

Nitro 提供了一个内置的 fetch API,可用于从服务器端点或其他来源获取数据。它建立在 unjs/ofetch 之上。

用法

¥Usage

在你的处理程序中,你只需调用 $fetch 函数即可触发请求。响应将被自动解析。

¥In your handler, you just have to call the $fetch function to make a request. The response will be automatically parsed.

Router Handler
export default defineEventHandler(async (event) => {
  const data = await $fetch('https://ungh.cc/orgs/unjs/repos')

  return data
})

你可以将泛型传递给 $fetch 函数以获得更好的类型推断。

¥You can pass a generic type to the $fetch function to get a better type inference.

Router Handler
import { Repo } from '~/types'

export default defineEventHandler(async (event) => {
  const data = await $fetch<Repo[]>('https://ungh.cc/orgs/unjs/repos')

  return data
})

你可以将许多选项传递给 $fetch 函数,例如方法、标头、正文、查询等。

¥You can pass many options to the $fetch function like the method, headers, body, query, etc.

Router Handler
import { Repo } from '~/types'

export default defineEventHandler(async (event) => {
  const data = await $fetch<Repo[]>('https://api.github.com/markdown', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json'
    },
    body: {
      text: 'Hello **world**!'
    }
  })

  return data
})

更多关于 $fetch 函数用法的信息,请参阅 unjs/ofetch 文档。

¥See more about the usage of the $fetch function in the unjs/ofetch documentation.

服务器内获取

¥In-Server fetch

你还可以使用 $fetch 函数向其他处理程序触发内部请求。

¥You can also use the $fetch function to make internal requests to other handlers.

Router Handler
export default defineEventHandler(async (event) => {
  const data = await $fetch('/api/users')

  return data
})

实际上,由于 unjs/unenv 的存在,不会触发任何获取请求,而是直接调用处理程序。这有助于避免 HTTP 请求开销。

¥In reality, no fetch request is made and the handler is directly called, thanks to unjs/unenv. This is useful to avoid making HTTP request overhead.