There are two problems with your example code:
- You should not set status code 101. Status code 101 means "switching protocols", i.e. the server is going to begin speaking something other than HTTP. This is used, for example, with WebSockets. But, your example code doesn't use a different protocol -- it's just regular HTTP with a streaming response body. The Workers runtime does not support switching protocols except to WebSocket, so it will refuse to serve your 101 status code, and will instead serve an error to the client.
- You are calling
getWriter()
on every interval, but you can only have one Writer, so on intervals after the first, the call fails. You should instead call getWriter()
once before setting the interval, then reuse that writer.
Both of these problems show up as errors in the JavaScript console when running your code in the preview (e.g. on cloudflareworkers.com, or in the Cloudflare dashboard, or using wrangler preview
or wrangler dev
). I recommend using the preview to debug your code, as it can tell you about errors that are invisible to the client.
The following code works for me in the preview -- text gets added to the response every 5 seconds as expected:
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const { readable, writable } = new TransformStream();
const encoder = new TextEncoder();
const writer = writable.getWriter();
setInterval(() => {
writer.write(encoder.encode(`data: hello
`));
}, 5000);
return new Response(readable);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…