useRequestFetch

使用 useRequestFetch 可组合组件转发服务器端获取请求的上下文和标头。

你可以使用 useRequestFetch 在发出服务器端获取请求时转发请求上下文和标头。

¥You can use useRequestFetch to forward the request context and headers when making server-side fetch requests.

发出客户端获取请求时,浏览器会自动发送必要的标头。但是,在服务端渲染期间发出请求时,出于安全考虑,我们需要手动转发标头。

¥When making a client-side fetch request, the browser automatically sends the necessary headers. However, when making a request during server-side rendering, due to security considerations, we need to forward the headers manually.

在请求中,如果标头为 not meant to be forwarded,则标头将为 not be included。例如,这些标头包括:transfer-encodingconnectionkeep-aliveupgradeexpecthostaccept
useFetch 可组合项在后台使用 useRequestFetch 自动转发请求上下文和标头。
<script setup lang="ts">
// This will forward the user's headers to the `/api/cookies` event handler
// Result: { cookies: { foo: 'bar' } }
const requestFetch = useRequestFetch()
const { data: forwarded } = await useAsyncData(() => requestFetch('/api/cookies'))

// This will NOT forward anything
// Result: { cookies: {} }
const { data: notForwarded } = await useAsyncData(() => $fetch('/api/cookies')) 
</script>
在浏览器中,客户端导航时,useRequestFetch 的行为与常规 $fetch 相同。