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

bq3bfh9z  于 2023-04-20  发布在  其他
关注(0)|答案(1)|浏览(172)

我有一个像这样的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结果?

lqfhib0f

lqfhib0f1#

问题的发生是因为默认的nextJs服务器默认压缩了所有内容。
只需在writeHead阶段中添加'Content-Encoding': 'none',一切都将如您所愿。

相关问题