const output = document.getElementById("output"); fetch("http://app-test.wisdompulse.cn/api/v1/llm/demo", { method: "POST", headers: { "Content-Type": "application/json", "Accept": "text/event-stream", "Authorization": "Bearer test" }, body: JSON.stringify({}) }).then(response => { const reader = response.body.getReader(); const decoder = new TextDecoder("utf-8"); let buffer = ""; function read() { reader.read().then(({ done, value }) => { if (done) { output.textContent += "\n[连接结束]"; return; } buffer += decoder.decode(value, { stream: true }); // 拆解成 SSE 事件格式:每段以 \n\n 分隔 const parts = buffer.split('\n\n'); buffer = parts.pop(); // 留给下一次未完整的部分 for (const part of parts) { const line = part.trim(); if (line.startsWith('data:')) { const jsonStr = line.substring(5).trim(); try { const data = JSON.parse(jsonStr); output.textContent += `收到:${data.content || '[无内容]'}\n`; } catch (e) { output.textContent += `解析失败:${jsonStr}\n`; } } } read(); }); } read(); });