mirror of
https://github.com/nuxt/nuxt.git
synced 2024-11-25 23:22:02 +00:00
docs: added recipe for consuming SSE via POST request (#27422)
This commit is contained in:
parent
c1565e2d20
commit
3af52b0375
@ -623,3 +623,37 @@ const { data } = await useFetch('/api/superjson', {
|
||||
})
|
||||
</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)
|
||||
}
|
||||
```
|
||||
|
Loading…
Reference in New Issue
Block a user