Nuxt 使用ofetch在你的 Vue 应用或 API 路由中,全局暴露 $fetch 辅助函数,用于发起 HTTP 请求。
$fetch 来获取内部 API 路由将直接调用相关函数(模拟请求),节省了额外的 API 调用。$fetch 而不将其包装在 useAsyncData 中会导致数据被获取两次:最初在服务器上,然后在客户端在水合作用期间再次获取,因为 $fetch 不会将状态从服务器传输到客户端。因此,由于客户端必须再次获取数据,因此将在两侧执行获取。我们建议使用 useFetch 或 useAsyncData + $fetch 来防止在获取组件数据时重复获取数据。
<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>
你可以在任何仅在客户端执行的方法中使用 $fetch。
<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 调用带有自签名证书的(外部)HTTPS URL,则需要在环境中设置 NODE_TLS_REJECT_UNAUTHORIZED=0。当我们在浏览器中调用 $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>
export default defineEventHandler((event) => {
const foo = getCookie(event, 'foo')
// ... Do something with the cookie
})
如果需要在服务器上传递请求头和 cookie,则必须手动传递它们
<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)。