我该如何在SvelteKit中实现服务器发送事件(SSE)?

6

我找不到一个不使用自定义express服务器的SvelteKit教程。有没有其他带有API端点的替代方案?

我已经尝试设置API端点,但是当数据发生更改时,我无法使其发送更新。

2个回答

6

你可能需要返回一个ReadableStream,以便你可以将更新写入其中。这样连接就不会关闭。

目前有一个未解决的问题,需要更多关于此方面的文档。


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', 
        }
    })
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接