JavaScript is required
Blog About

前端接收SSE (Server-Sent Events)实现对接AI对话功能

2024/07/11
3 mins read
See this issue
# Javascript
Back

EventSource只支持GET方式请求,不支持POST方式,本次解决了使用POST方式请求SSE的需求

对接的主要难点在于解析接口返回的数据格式,不能直接使用,而且使用eval()JSON.parse都失败了,经过尝试,在不使用第三方库的情况下可以使用TextDecoder + JSON.parse来解析数据


async initEventSource(question) {
  const params = {
    query: question,
    stream: true,
  }
  const response = await fetch(
    `API_URL`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify(params),
    }
  )
  const stream = response.body
  const reader = stream.getReader()
  const readChunk = () => {
    reader
      .read()
      .then(({ value, done }) => {
        if (done) {
          console.log('Stream finished')
          return
        }
        const chunkString = new TextDecoder().decode(value)
        if (chunkString.startsWith('data:')) {
          const target = chunkString.split('data: ')[1]
		 // 业务规定的数据结构
          const { answer, final_answer } = JSON.parse(target)
           if (answer) {
            const lastAnswer = this.chatData[this.chatData.length - 1] .content
          	const date = this.chatData[this.chatData.length - 1].date || new Date().toLocaleString()
             this.chatData.pop()
             this.chatData.push({
               content: lastAnswer + answer,
               role: 'ai',
               date,
             })
           }
        }
        readChunk()
      })
      .catch((error) => {
        console.error(error)
      })
  }
  readChunk()
},