docs: added recipe for consuming SSE via POST request (#27422)

This commit is contained in:
JD Solanki 2024-06-06 18:17:31 +05:30 committed by GitHub
parent c1565e2d20
commit 3af52b0375
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -623,3 +623,37 @@ const { data } = await useFetch('/api/superjson', {
}) })
</script> </script>
``` ```
## 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<ReadableStream>('/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)
}
```