admin管理员组

文章数量:1355754

so I'm using server-side events to push messages from the server to the frontend. For front end. I'm using fetch to start the stream, like this

const response = await fetch(`${API_URL}/hello`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': api.defaults.headersmon['Authorization'],
      'Accept': 'text/event-stream',
    },
    body: JSON.stringify(input)
  });

  if (!response.ok) {
    const errorBody = await response.json();
    throw new Error(`generateImage HTTP error! status: ${response.status} ${response.statusText}. Details: ${JSON.stringify(errorBody)}`);
  }

  const reader = response.body.getReader();
  const decoder = new TextDecoder();
// everything else the same

How do we close the stream if using fetch? Currently I'm using AbortController but I don't think it's the best practice. Also every time the steam closes, an error will appear on the console log, which is not very nice.

FYI, I used fetch instead of Axios because Axios does not support event stream on Safari and I don't use EventSource either because EventSource only works with GET request, while my server expose a POST request, and I cannot change that.

本文标签: javascriptHow to close stream with serverside event using fetchStack Overflow