从流中获取的数据格式如下
小程序调用SSE接口
const requestTask = wx.request({
url: `xxx`,
enableChunked: true,
method: "GET",
timeout: '120000',
success(res) {
console.log(res.data)
},
fail: function (error) {
console.error(error);
},
complete: function () {
console.log('请求完成', str);
}
})
requestTask.onChunkReceived(res => {
console.log( res, res.data);
})
我这边接收到的数据类型为Uint8Array,需要处理成text文本(如上图)
requestTask.onChunkReceived(res => {
console.log( res, res.data);
let arrayBuffer = res.data;
let decoder = new TextDecoder('utf-8');
let text = decoder.decode(arrayBuffer);
const eventRegex = /event:data\ndata:"data:(.*?)"/g;
const eventRegexErr = /event:600\ndata:"(.*?)"/g;
let matches = [];
let match;
if (text.indexOf('600') != -1) {
while ((match = eventRegexErr.exec(text)) !== null) {
wx.showToast({
title: match[1],
})
matches.push(match[1]);
}
str = str + matches.join('')
} else {
while ((match = eventRegex.exec(text)) !== null) {
matches.push(match[1]);
}
str = str + matches.join('')
console.log(text, str);
}
})
使对话有打字机效果
参考自:小程序实现 ChatGPT 聊天打字兼自动滚动效果
handleRequestResolve(result) {
this.setData({
currentContent: ''
})
const contentCharArr = result.trim().split("")
this.showText(0, contentCharArr);
},
showText(key = 0, value) {
if (key >= value.length) {
return;
}
this.setData({
currentContent: this.data.currentContent + value[key],
})
setTimeout(() => {
this.showText(key + 1, value);
}, 50);
},
完整代码
getDataStream(data) {
let str = ''
let that = this
const requestTask = wx.request({
enableChunked: true,
url: 'xxx',
enableChunked: true,
method: "GET",
responseType: "arraybuffer",
timeout: '120000',
success(res) {
console.log(res.data)
},
fail: function (error) {
console.error(error);
},
complete: function () {
console.log('请求完成', str);
}
})
requestTask.onChunkReceived(res => {
console.log(res, res.data);
let arrayBuffer = res.data;
let decoder = new TextDecoder('utf-8');
let text = decoder.decode(arrayBuffer);
const eventRegex = /event:data\ndata:"data:(.*?)"/g;
const eventRegexErr = /event:600\ndata:"(.*?)"/g;
let matches = [];
let match;
if (text.indexOf('600') != -1) {
while ((match = eventRegexErr.exec(text)) !== null) {
wx.showToast({
title: match[1],
})
matches.push(match[1]);
}
str = str + matches.join('')
} else {
while ((match = eventRegex.exec(text)) !== null) {
matches.push(match[1]);
}
str = str + matches.join('')
console.log(text, str);
}
that.handleRequestResolve(str)
})
requestTask.offChunkReceived(res => {
console.log('事件完成状态');
})
},
handleRequestResolve(result) {
this.setData({
currentContent: ''
})
const contentCharArr = result.trim().split("")
this.showText(0, contentCharArr);
},
showText(key = 0, value) {
if (key >= value.length) {
return;
}
this.setData({
currentContent: this.data.currentContent + value[key],
})
setTimeout(() => {
this.showText(key + 1, value);
}, 50);
},