mirror of
https://github.com/nuxt/nuxt.git
synced 2025-02-12 19:58:10 +00:00
docs: fix typo and improve data fetching examples (#30935)
This commit is contained in:
parent
4150a4cb5c
commit
31e72ded69
@ -90,22 +90,35 @@ Read more about `$fetch`.
|
||||
|
||||
### Pass Client Headers to the API
|
||||
|
||||
During server-side-rendering, since the `$fetch` request takes place 'internally' within the server, it won't include the user's browser cookies.
|
||||
When calling `useFetch` on the server, Nuxt will use [`useRequestFetch`](/docs/api/composables/use-request-fetch) to proxy client headers and cookies (with the exception of headers not meant to be forwarded, like `host`).
|
||||
|
||||
We can use [`useRequestHeaders`](/docs/api/composables/use-request-headers) to access and proxy cookies to the API from server-side.
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const { data } = await useFetch('/api/echo');
|
||||
</script>
|
||||
```
|
||||
|
||||
The example below adds the request headers to an isomorphic `$fetch` call to ensure that the API endpoint has access to the same `cookie` header originally sent by the user.
|
||||
```ts
|
||||
// /api/echo.ts
|
||||
export default defineEventHandler(event => parseCookies(event))
|
||||
```
|
||||
|
||||
Alternatively, the example below shows how to use [`useRequestHeaders`](/docs/api/composables/use-request-headers) to access and send cookies to the API from a server-side request (originating on the client). Using an isomorphic `$fetch` call, we ensure that the API endpoint has access to the same `cookie` header originally sent by the user's browser. This is only necessary if you aren't using `useFetch`.
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
const headers = useRequestHeaders(['cookie'])
|
||||
|
||||
async function getCurrentUser() {
|
||||
return await $fetch('/api/me', { headers: headers.value })
|
||||
return await $fetch('/api/me', { headers })
|
||||
}
|
||||
</script>
|
||||
```
|
||||
|
||||
::tip
|
||||
You can also use [`useRequestFetch`](/docs/api/composables/use-request-fetch) to proxy headers to the call automatically.
|
||||
::
|
||||
|
||||
::caution
|
||||
Be very careful before proxying headers to an external API and just include headers that you need. Not all headers are safe to be bypassed and might introduce unwanted behavior. Here is a list of common headers that are NOT to be proxied:
|
||||
|
||||
@ -115,10 +128,6 @@ Be very careful before proxying headers to an external API and just include head
|
||||
- `cf-connecting-ip`, `cf-ray`
|
||||
::
|
||||
|
||||
::tip
|
||||
You can also use [`useRequestFetch`](/docs/api/composables/use-request-fetch) to proxy headers to the call automatically.
|
||||
::
|
||||
|
||||
## `useFetch`
|
||||
|
||||
The [`useFetch`](/docs/api/composables/use-fetch) composable uses `$fetch` under-the-hood to make SSR-safe network calls in the setup function.
|
||||
|
Loading…
Reference in New Issue
Block a user