fetch-event-source icon indicating copy to clipboard operation
fetch-event-source copied to clipboard

net::ERR_HTTP2_PROTOCOL_ERROR 200 (OK) and abortController don't work

Open YakumoAoi opened this issue 1 year ago • 4 comments
trafficstars

const abortController = new AbortController()
  await fetchEventSource(
    `https://xxx/xx/xx/xx?query=${questionSended}&dialog_id=${this.currentDialogID}&is_stream=1`,
    {
      headers: {
        Authorization: userinfo.token
      },
      signal: abortController.signal,
      openWhenHidden: true,
      onopen: async response => {
        console.log('onopen', response)
        if (response.status !== 200) {
          throw new Error(`${response.status}(${response.statusText})`)
        }
        return
      },
      onmessage: res => {
        const data = JSON.parse(res.data)
        console.log(data)
        if (data.plugin_id) return
        if (data.error_code) {
          throw new Error(`${data.error_code}(${data.error_msg})`)
        }
        if (data.prompt) {
          this.relatedQuestion = data.prompt
        } else {
     
        }
      },
      onclose: () => {
        console.log('closed')
      },
      onerror: err => {
        console.log('err', err)
        if (abortController.signal.aborted) return
        this.dialogDetailList[contextIndex].answer =
          'error'
        abortController.abort()
      }
    }
  )

The error occured in the middle of request, and the browser start another request to continue receiving stream data. And the same error occured. such back and forth And l can read true value of 'abortController.signal.aborted' in error callback, but the request still continue

YakumoAoi avatar Mar 18 '24 08:03 YakumoAoi

same error

SadEaston avatar Mar 19 '24 03:03 SadEaston

Me too. Have you solved the problem?

Cai-Quan avatar Apr 22 '24 09:04 Cai-Quan

'use client';

import { fetchEventSource } from '@microsoft/fetch-event-source';
import { useEffect, useState } from "react";

export default function Home() {

  const [text, setText] = useState('')

  useEffect(() => {
    const ctrl = new AbortController();
    fetchEventSource('/api/sse4', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        foo: 'bar'
      }),
      signal: ctrl.signal,
      onmessage: function (event) {
        console.log('Received message:', event.data)
        setText((pre) => pre + event.data);
      }
    });

    return () => {
      ctrl.abort()
    }
  }, [])

  return (
    <p>{text}</p>
  );
}

mqyqingfeng avatar May 23 '24 07:05 mqyqingfeng

https://github.com/Azure/fetch-event-source/issues/46 https://github.com/Azure/fetch-event-source/issues/24

It seems that you need to throw an error in the onerror callback

wooly99 avatar Jun 17 '24 10:06 wooly99