$fetch
Nuxt 使用 ofetch 全域性公開 $fetch 輔助函式,用於發起 HTTP 請求。
Nuxt 使用ofetch全域性公開 $fetch
輔助函式,用於在 Vue 應用或 API 路由中發起 HTTP 請求。
在伺服器端渲染期間,呼叫
$fetch
來獲取你的內部 API 路由 將直接呼叫相關函式(模擬請求),節省了一次額外的 API 呼叫。在元件中使用
$fetch
而不將其包裝在 useAsyncData
中會導致資料被獲取兩次:最初在伺服器上,然後在客戶端在水合作用期間再次獲取,因為 $fetch
不會將狀態從伺服器傳輸到客戶端。因此,獲取操作將在兩端執行,因為客戶端必須再次獲取資料。使用
我們建議使用 useFetch
或 useAsyncData
+ $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>
你可以在任何只在客戶端執行的方法中使用 $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
呼叫帶有自簽名證書的(外部)HTTPS URL,你需要將環境變數 NODE_TLS_REJECT_UNAUTHORIZED=0
設定為你的環境。傳遞 Headers 和 Cookies
當我們在瀏覽器中呼叫 $fetch
時,使用者請求頭,如 cookie
將直接傳送到 API。
然而,在伺服器端渲染期間,由於存在伺服器端請求偽造 (SSRF) 或身份驗證濫用等安全風險,$fetch
不會包含使用者的瀏覽器 cookies,也不會傳遞 fetch 響應中的 cookies。
<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
})
如果需要在伺服器上轉發請求頭和 cookies,你必須手動傳遞它們
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
來代理請求頭和 cookies(除了不應轉發的請求頭,例如 host
)。