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

问题描述 投票:0回答:1

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

编辑: 虽然

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

reactjs next.js server-sent-events
1个回答
1
投票

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

只需在您的

'Content-Encoding': 'none'
阶段添加
writeHead
,一切都会如您所愿。

© www.soinside.com 2019 - 2024. All rights reserved.