$fetch

源文件
Nuxt 使用 ofetch 来全局提供 $fetch 辅助函数,用于发起 HTTP 请求。

Nuxt 使用ofetch全局提供 $fetch 辅助函数,以便在 Vue 应用或 API 路由中发起 HTTP 请求。

在服务端渲染期间,调用 $fetch 来获取内部 API 路由 将直接调用相关函数(模拟请求),从而节省额外的 API 调用
在组件中直接使用 $fetch 而不使用 useAsyncData 包装,会导致数据被获取两次:首先在服务端获取,然后在客户端激活(hydration)期间再次获取,因为 $fetch 不会在服务端和客户端之间传输状态。因此,fetch 将在两端执行,因为客户端必须再次获取数据。

使用

我们建议使用 useFetchuseAsyncData + $fetch,以防止在获取组件数据时出现重复请求。

app/app.vue
<script setup lang="ts">
// During SSR data is fetched twice, once on the server and once on the client.
const dataTwice = await $fetch('/api/item')

// During SSR data is fetched only on the server side and transferred to the client.
const { data } = await useAsyncData('item', () => $fetch('/api/item'))

// You can also useFetch as shortcut of useAsyncData + $fetch
const { data } = await useFetch('/api/item')
</script>
文档 > 4 X > 入门 > 数据获取中阅读更多信息。

你可以在任何仅在客户端执行的方法中使用 $fetch

app/pages/contact.vue
<script setup lang="ts">
async function contactForm () {
  await $fetch('/api/contact', {
    method: 'POST',
    body: { hello: 'world' },
  })
}
</script>

<template>
  <button @click="contactForm">
    Contact
  </button>
</template>
$fetch 是 Nuxt 中进行 HTTP 调用的首选方式,不再推荐使用:@nuxt/http等等@nuxtjs/axios这些是为 Nuxt 2 设计的。
如果你在开发环境中使用 $fetch 调用带有自签名证书的(外部)HTTPS URL,则需要设置环境变量 NODE_TLS_REJECT_UNAUTHORIZED=0

传递请求头(Headers)和 Cookie

当我们在浏览器中调用 $fetch 时,用户请求头(如 cookie)将被直接发送到 API。

然而,在服务端渲染期间,由于服务端请求伪造 (SSRF)身份验证滥用等安全风险,$fetch 不会包含用户的浏览器 Cookie,也不会传递来自 fetch 响应的 Cookie。

<script setup lang="ts">
// This will NOT forward headers or cookies during SSR
const { data } = await useAsyncData(() => $fetch('/api/cookies'))
</script>

如果需要在服务端转发请求头和 Cookie,必须手动传递它们。

app/pages/index.vue
<script setup lang="ts">
// This will forward the user's headers and cookies to `/api/cookies`
const requestFetch = useRequestFetch()
const { data } = await useAsyncData(() => requestFetch('/api/cookies'))
</script>

但是,当在服务端使用相对 URL 调用 useFetch 时,Nuxt 会使用 useRequestFetch 来代理请求头和 Cookie(除了不应转发的请求头,如 host)。