$fetch
Nuxt 使用 ofetch 來全域公開 $fetch 輔助程式,以進行 HTTP 請求。
Nuxt 使用 ofetch 來全域公開 $fetch
輔助程式,以便在您的 Vue 應用程式或 API 路由中進行 HTTP 請求。
在伺服器端渲染期間,呼叫
$fetch
以獲取您的內部 API 路由 將直接呼叫相關函數(模擬請求),從而節省額外的 API 呼叫。在元件中使用
$fetch
而不使用 useAsyncData
包裝它,會導致資料被獲取兩次:最初在伺服器端,然後在用戶端水合期間再次獲取,因為 $fetch
不會將狀態從伺服器傳輸到用戶端。因此,獲取將在兩端執行,因為用戶端必須再次獲取資料。用法
我們建議使用 useFetch
或 useAsyncData
+ $fetch
來防止在獲取元件資料時發生雙重資料獲取。
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>
您可以在任何僅在用戶端執行的方法中使用 $fetch
。
pages/contact.vue
<script setup lang="ts">
function contactForm() {
$fetch('/api/contact', {
method: 'POST',
body: { hello: 'world '}
})
}
</script>
<template>
<button @click="contactForm">Contact</button>
</template>
如果您使用
$fetch
在開發中呼叫具有自我簽署憑證的(外部)HTTPS URL,您將需要在您的環境中設定 NODE_TLS_REJECT_UNAUTHORIZED=0
。傳遞標頭和 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,您必須手動傳遞它們
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
)。