如何在 NextJS api 中转发服务器发送的事件

Bra*_*zic 9 server-sent-events reactjs next.js

我有一个像这样的 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();
    };
  }
});

Run Code Online (Sandbox Code Playgroud)

本质上,我试图在需要授权承载令牌的后端 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>;
}
Run Code Online (Sandbox Code Playgroud)

问题出在哪里?客户端没有收到任何信息。当我尝试res.end()在 API 端调用时,客户端会收到一个事件,但事件流会不断重新连接......就像每秒一样。基本上,连接没有保持活动状态。我如何转发我的 SSE 结果?

编辑: 虽然标头no-cache, no-transform中的属性Content-Type解决了事件的接收问题,但未关闭的服务器端连接问题仍然存在。本质上,在客户端断开连接时,服务器端 SSE 连接也应该关闭。

Jer*_*ser 1

出现问题是因为默认的 nextJs 服务器默认压缩所有内容。

只需添加'Content-Encoding': 'none'您的writeHead舞台,一切都会按照您的意愿进行。