1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

Server Sent Event; `EventSource.onmessage` not firing

Discussão em 'Angular' iniciado por noamyg, Junho 2, 2025.

  1. noamyg

    noamyg Guest

    I'm trying to use the following example of Server Sent Events. Seems like the server is emitting the data, but the event is not firing and no data is recorded in the event stream (through the developer tools).

    Angular code (service):

    getAlertsEvent(fieldIds: Guid[]): Observable<responseModel.LoanAlert> {
    return new Observable(obs => {
    fieldIds.forEach(fieldId => {
    const source = new EventSource(`http://localhost:3000/loan/alerts/${fieldId}`);
    alert('Succesfully creates the EventSource, I see reuslt 200 in Networking tab but with 0 events');
    source.onmessage = (ev): void => {
    this.zone.run(() => {
    alert('This alert will not happen');
    obs.next(ev.data);
    });
    };
    source.onerror = (err): void => this.zone.run(() => obs.error(err));
    // Also tried this way with no luck:
    // source.addEventListener('message', (event) => {
    // obs.next(event.data);
    // });
    });
    });
    }


    Component:

    this.loansService.getAlertsEvent(this.fields.map(field => field.fieldId)).subscribe(alert => {
    console.log(alert);
    });


    Node.js code:

    const express = require('express');
    const parser = require('body-parser');
    const app = express();
    const EventEmitter = require('events');

    const Stream = new EventEmitter();

    app.unsubscribe(parser.json());
    app.use(
    parser.urlencoded({
    extended: true,
    })
    );

    app.get('/loan/alerts/:fieldId', function(req, res) {
    res.writeHead(200, {
    'Content-Type': 'text/event-stream',
    'Cache-Control': 'no-cache',
    'Access-Control-Allow-Origin': "*",
    Conection: 'keep-alive'
    });

    Stream.on(req.params.fieldId, function(event, data) {
    res.write(JSON.stringify(data));
    });
    });

    setInterval(function() {
    const item = {
    formId: 51415,
    alertId: 'asdfasdfasdf',
    messageStatus: 'NEW',
    messageType: 'ACTION_MESSAGE_FROM_SERVER',
    actionType: 'NAVIGATION',
    message: 'New Message!',
    archiverId: '12345',
    documentCode: 3,
    from: 'Internal Server Message',
    messageTimestamp: new Date().toJSON(),
    markedAsRead: false,
    };
    Stream.emit('aed29580-09fd-e411-b8e1-e61f13cf5d4b', 'message', item);
    }, 5000);

    app.listen(3000);

    console.log('Express E2e Mock server is running');


    When manually going to http://localhost:3000/loan/alerts/aed29580-09fd-e411-b8e1-e61f13cf5d4b I'm seeing the messages printed to the screen, so I guess that this is either an Angular or a missing security header. Thanks!

    Continue reading...

Compartilhe esta Página