1.安装fetch-event-source插件
npm install @microsoft/fetch-event-source
2.使用方法如下
fetchEventSource('https://spark-api-open.xf-yun.com/v1/chat/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', "Authorization": "Bearer apikey", }, body: JSON.stringify(form), openWhenHidden: true, onopen(ops) { // console.log(ops); }, onmessage(res) { // eventSource.close(); if (res.data == '[DONE]') { data.disabledSend = false; } else { let resdata = JSON.parse(res.data); textS+= resdata.choices[0].delta.content; data.messages[msglen + 1] = { sender: 'admin', text: textS, msglen }; // console.log(data.messages) } }, onerror(err) { throw Error(err); } });