1
This commit is contained in:
@@ -2,11 +2,11 @@ import httpEnv from "./auth/env"
|
||||
import { getToken, removeToken } from "./auth/manageToken"
|
||||
const baseApi = {
|
||||
//开发版
|
||||
develop: "https://curainwxapp.test.tuzuu.com/api",
|
||||
develop: "https://kairos-wx.test.tuzuu.com/api",
|
||||
// 体验版
|
||||
trial: "https://curainwxapp.test.tuzuu.com/api",
|
||||
trial: "https://kairos-wx.test.tuzuu.com/api",
|
||||
// 正式版
|
||||
release: "https://yidaojia.cells.org.cn/api"
|
||||
release: "https://kairos-wx.test.tuzuu.com/api",
|
||||
}
|
||||
//获取当前环境的接口前缀
|
||||
export const baseUrl = baseApi[httpEnv]
|
||||
@@ -82,4 +82,65 @@ request.post = function (url, options) {
|
||||
})
|
||||
}
|
||||
|
||||
//流式
|
||||
let lastChunk = '' //流可能会被截断,需要补充
|
||||
export function streamRequest(url, data, onChunkReceived) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const token = getToken()
|
||||
let header = {}
|
||||
if (token) {
|
||||
header.Authorization = 'Bearer ' + token;
|
||||
}
|
||||
let requestTask = wx.request({
|
||||
url: baseUrl + url,
|
||||
data: data || {},
|
||||
method: 'POST',
|
||||
header,
|
||||
timeout: 100000,
|
||||
responseType: "arraybuffer",
|
||||
enableChunked: true, //关键!开启流式传输模式
|
||||
success: () => {
|
||||
resolve()
|
||||
},
|
||||
fail: (e) => {
|
||||
console.log(e);
|
||||
reject()
|
||||
}
|
||||
})
|
||||
//处理流
|
||||
if (onChunkReceived) {
|
||||
lastChunk = ''
|
||||
requestTask.onChunkReceived((response) => {
|
||||
let data = response.data;
|
||||
// console.log(decodeStream(data));
|
||||
onChunkReceived(decodeStream(data))
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
//流素具解码
|
||||
function decodeStream(data) {
|
||||
let uint8Array = new Uint8Array(data); // 将 ArrayBuffer 转换为 Uint8Array
|
||||
let responseText = decodeURIComponent(escape(String.fromCharCode.apply(null, uint8Array))); // 使用 apply 扩展字节
|
||||
// 处理数据,移除前缀等操作
|
||||
if (lastChunk) {
|
||||
responseText = "data: " + lastChunk + responseText
|
||||
lastChunk = ""
|
||||
}
|
||||
// 处理数据,移除前缀等操作
|
||||
responseText = responseText.replaceAll("data: ", '');
|
||||
let jsonStrings = responseText.trim().split(/\n+/);
|
||||
// 过滤掉解析失败的部分
|
||||
let jsonArray = jsonStrings.map(jsonStr => {
|
||||
try {
|
||||
return JSON.parse(jsonStr);
|
||||
} catch (e) {
|
||||
lastChunk = jsonStr
|
||||
console.error('JSON格式不正确(已做兼容处理):');
|
||||
return null; // 如果解析失败,返回null
|
||||
}
|
||||
}).filter(item => item !== null);
|
||||
return jsonArray
|
||||
}
|
||||
|
||||
export default request
|
||||
Reference in New Issue
Block a user