skip to Main Content

These codes are running perfectly in localhost. Messages come after each res.write. But these codes not running properly when I put to real server. All messages is coming before close EventSource connection. So running like normal HTTP. Where is my mistake ?

Front-End:

  const event_source = new EventSource("https://test.com/sse");

  event_source.addEventListener('message', (message) => {
      console.log(message)
    }, false);

  event_source.addEventListener('open', (_e) => {
      console.log('EventSource Connected !');
    }, false);

  event_source.addEventListener('error', (err) => {
      //Close Event Source
    }, false);

Back-End:

let aa = 0
setInterval(() => {
  aa++
  if (aa === 5) {
    return r(aa)
  }
  res.write(`event: aan`)
  res.write(`data: sefa -> ${aa}nn`)
}, 1000)

Nginx Conf:

  location /sse {
    proxy_pass http://localhost:3005;
  }

2

Answers


  1. Chosen as BEST ANSWER

    I solved my problem. When I edited nginx.conf, it run

      location /sse {
        proxy_pass http://localhost:3005;
        
        # For EventSource
        proxy_buffering off;
        proxy_read_timeout 86400s;
        sendfile off;
        tcp_nopush on;
        keepalive_timeout 65;
        types {
          text/event-stream   sse;
        }
      }
    

  2. While working on the chatGPT integration demo, I encountered the same issue.
    I am using Angular & Spring Boot and useing server sent events to connect,
    which is also used by OpenAI.
    When running locally, there were no issues.

    However, when deployed on the cloud environment (Alibaba Cloud),
    the front-end had to wait for all the back-end information to be sent before displaying it.

    This was due to the use of nginx (reverse proxy) and SLB (load balancing),
    which took a long time to troubleshoot.
    Eventually,
    the problem was found to be with nginx,
    and the issue was resolved by adjusting its settings.

    Thank you so much for this solution.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search