一、直接上代码
async sendRequest(messageId, content, questionId, questionType, aiToken, innerIndex) {
let that = this;
const response = await fetch(
`${
process.env.VUE_APP_WEB_API
}/urlf_rnd=${new Date().getTime()}&message_id=${messageId}&question_id=${messageId}&question_type=${questionType}&stream=true`,
{
method: 'GET',
cache: 'no-cache',
headers: {
'Content-Type': 'text/event-stream',
aiToken: aiToken,
},
}
).then(response => {
const reader = response.body.getReader();
let buffer = '';
let resultWord = '';
function read() {
reader
.read()
.then(({ done, value }) => {
that.loading = false;
that.scrollFlag = false;
if (done) {
if (buffer) {
try {
const lastChunk = buffer.trim().replace(/^data:/, '');
const json = JSON.parse(lastChunk);
console.log(json);
} catch (e) {
console.error('Error parsing last chunk:', e);
}
}
console.log('Stream complete');
that.requestRecomme1(messageId, innerIndex);
return;
}
const chunk = new TextDecoder().decode(value);
buffer += chunk;
const lines = buffer.split(/\r?\n/);
let fullLines = lines.slice(0, -1);
buffer = lines.slice(-1)[0];
console.log(fullLines, 'fullLines');
fullLines.forEach(line => {
const jsonString = line.trim().replace(/^data:/, '');
try {
if (line) {
const json = JSON.parse(jsonString);
console.log(json.data.content, json, 'json');
resultWord += json.data.content;
that.$set(that.messageList, innerIndex, {
type: 'right',
session_id: json.data.session_id,
message_id: json.data.message_id,
reply_id: json.data.reply_id,
message: resultWord,
source: [],
sourceEdit: [],
question: [],
});
that.receiveMsg = that.messageList[innerIndex];
that.chcekScroll();
that.executeScroll(!that.scrollFlag);
}
} catch (e) {
console.error('Error parsing JSON:', e, 'in line:', line);
}
});
read();
})
.catch(error => console.error('Error reading stream:', error));
}
read();
});
},