docs(data-fetching): fix and simplify cookie proxy example (#5770)

This commit is contained in:
Mourad EL CADI 2022-08-15 15:54:09 +01:00 committed by GitHub
parent 3920065bff
commit e2745f6d75
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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>
```