laz*_*zar 6 node.js server-sent-events sveltekit
如果不使用自定义 Express 服务器,我找不到 SvelteKit 的教程。有 API 端点的替代方案吗?
我尝试自己设置 API 端点,但无法让它在数据更改时发送更新。
小智 5
感谢@Paolo 的想法。这是一个更具体的例子:
在您的+server.js文件中,实现以下代码:
// SSE only supports GET request
export async function GET({ url }) {
const stream = new ReadableStream({
start(controller) {
// You can enqueue multiple data asynchronously here.
const myData = ["abc", "def"]
myData.forEach(data => {
controller.enqueue(`data: ${data}\n\n`)
})
controller.close()
},
cancel() {
// cancel your resources here
}
});
return new Response(stream, {
headers: {
// Denotes the response as SSE
'Content-Type': 'text/event-stream',
// Optional. Request the GET request not to be cached.
'Cache-Control': 'no-cache',
}
})
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3845 次 |
| 最近记录: |