我有一个类似于这样的Next.js api(/api/events/index.js
):
import EventSource from 'eventsource';
import { getAccessToken, withApiAuthRequired } from '@auth0/nextjs-auth0';
export default withApiAuthRequired(async function handler(req, res) {
if (req.method === 'GET') {
const { accessToken } = await getAccessToken(req, res);
res.writeHead(200, {
Connection: 'keep-alive',
'Cache-Control': 'no-cache',
'Content-Type': 'text/event-stream',
});
const eventSource = new EventSource(
`http://localhost:8000/v1/event-stream`,
{ headers: { Authorization: `Bearer ${accessToken}` } },
);
eventSource.onmessage = (e) => {
res.write(`data: ${e.data}\n\n`);
// res.end();
};
}
});
基本上,我正在尝试在后端API SSE端点上发出请求,该请求需要一个授权承载令牌(最好,访问令牌应仅在Next.js API端可用)。收到事件后,它应在新的事件流响应中写入。
在React客户端代码中,我只需按如下订阅这些SSE:
const IndexPage = () => {
useEffect(() => {
const eventSource = new EventSource(`http://localhost:3000/api/events`);
eventSource.onmessage = (e) => {
console.log(e);
};
return () => {
eventSource.close();
};
}, []);
return <div></div>;
}
问题出在哪里?客户端没有收到任何信息。当我尝试在 API 端调用 res.end() 时,客户端会接收到一个事件,但事件流会不断重新连接,大约每秒钟一次。基本上,连接没有保持活动状态。我如何转发我的 SSE 结果?
http://localhost:8000/v1/event-stream
。这绝对是可怕的... - Branislav Lazicno-cache. no-transform
以及/api/events/index.js
中的这一部分:req.on("close", async () => { reader.cancel(); res.end(); });
- slumbering