From 3af52b0375d72531f81e84e0754970d1543937a0 Mon Sep 17 00:00:00 2001 From: JD Solanki Date: Thu, 6 Jun 2024 18:17:31 +0530 Subject: [PATCH] docs: added recipe for consuming SSE via POST request (#27422) --- docs/1.getting-started/6.data-fetching.md | 34 +++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/docs/1.getting-started/6.data-fetching.md b/docs/1.getting-started/6.data-fetching.md index 32976b1f29..84b36df3bf 100644 --- a/docs/1.getting-started/6.data-fetching.md +++ b/docs/1.getting-started/6.data-fetching.md @@ -623,3 +623,37 @@ const { data } = await useFetch('/api/superjson', { }) ``` + +## Recipes + +### Consuming SSE (Server Sent Events) via POST request + +::tip +If you're consuming SSE via GET request, you can use [`EventSource`](https://developer.mozilla.org/en-US/docs/Web/API/EventSource) or VueUse composable [`useEventSource`](https://vueuse.org/core/useEventSource/). +:: + +When consuming SSE via POST request, you need to handle the connection manually. Here's how you can do it: + +```ts +// Make a POST request to the SSE endpoint +const response = await $fetch('/chats/ask-ai', { + method: 'POST', + body: { + query: "Hello AI, how are you?", + }, + responseType: 'stream', +}) + +// Create a new ReadableStream from the response with TextDecoderStream to get the data as text +const reader = response.pipeThrough(new TextDecoderStream()).getReader() + +// Read the chunk of data as we get it +while (true) { + const { value, done } = await reader.read() + + if (done) + break + + console.log('Received:', value) +} +```