mirror of
https://github.com/nuxt/nuxt.git
synced 2025-02-16 21:58:19 +00:00
docs(data-fetching): fix and simplify cookie proxy example (#5770)
This commit is contained in:
parent
3920065bff
commit
e2745f6d75
@ -212,24 +212,20 @@ Here is a list of common headers that are NOT to be proxied:
|
||||
If you want to pass on/proxy cookies in the other direction, from an internal request back to the client, you will need to handle this yourself.
|
||||
|
||||
```ts [composables/fetch.ts]
|
||||
export const fetchWithCookie = async (url: string, cookieName: string) => {
|
||||
const response = await $fetch.raw(url)
|
||||
if (process.server) {
|
||||
const cookies = Object.fromEntries(
|
||||
response.headers.get('set-cookie')?.split(',').map((a) => a.split('='))
|
||||
)
|
||||
if (cookieName in cookies) {
|
||||
useCookie(cookieName).value = cookies[cookieName]
|
||||
}
|
||||
export const fetchWithCookie = async (url: string) => {
|
||||
const res = await $fetch.raw(url)
|
||||
const cookies = (res.headers.get('set-cookie') || '').split(',')
|
||||
for (const cookie of cookies) {
|
||||
appendHeader(useRequestEvent(), 'set-cookie', cookie)
|
||||
}
|
||||
return response._data
|
||||
return res._data
|
||||
}
|
||||
```
|
||||
|
||||
```vue
|
||||
<script setup lang="ts">
|
||||
// This composable will automatically pass on a cookie of our choice.
|
||||
const result = await fetchWithCookie("/api/with-cookie", "test")
|
||||
// This composable will automatically pass cookies to the client
|
||||
const result = await fetchWithCookie("/api/with-cookie")
|
||||
onMounted(() => console.log(document.cookie))
|
||||
</script>
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user