请问大佬们如何正确配置 Nginx 使其能够启用 SSE(server-sent-events)

12次阅读

共计 1002 个字符,预计需要花费 3 分钟才能阅读完成。

我在本地测试完全没有问题,本地的 nginx 监听 80 端口转发到 express 也是完全没有问题,但是直到启用 ssl,开启 443 端口后,服务端发送消息,客户端就无法接收了,完全找不到头绪,网上的例子都试了就是没有用
以下是我的 nginx 配置

server {
  listen 443 ssl http2;
  listen [::]:443 http2 ssl;
  server_name  www.mydomain.com;

  ssl_certificate /etc/letsencrypt/live/www.mydomain.com/fullchain.pem;
  ssl_certificate_key /etc/letsencrypt/live/www.mydomain.com/privkey.pem;

  access_log off;

  location / {
    proxy_pass http://127.0.0.1:3000/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "";
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
    proxy_buffering off;
    proxy_cache off;
    proxy_read_timeout 300s;
    chunked_transfer_encoding off;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
  }
}

我的服务端代码

eventRouter.get('/event/:userID', async (req, res) => {
  const headers: OutgoingHttpHeaders = {
    'Content-Type': 'text/event-stream',
    'Connection': 'keep-alive',
    "Cache-Control": 'no-cache',
    "X-Accel-Buffering": 'no'
  }
  res.writeHead(200, headers)
  res.write(JSON.stringify({ type: 'handshake'} satisfies IEventMessage))
}

有知道的大佬吗,实在不行我滚回 long-loop 了

正文完
 0