Close event not working when using Node.js request module for piping?

1.6k views Asked by At

I am currently developing two Node.js apps for my chat app: first one is API which handles backend logic and another app is client (frontend with Angular.JS) which uses the API.

Client app is using request module for proxying HTTP requests to API because I couldn't get them communicating with each other until I found this article: https://blog.javascripting.com/2015/01/17/dont-hassle-with-cors/.

API (subscribe to event stream):

var clientId = 0;
var clients = {};

app.get('/api/xyz', function(req, res) {

    console.log('start');

    req.socket.setTimeout(0x7FFFFFFF);

    res.writeHead(200, {
        'Content-Type': 'text/event-stream',
        'Cache-Control': 'no-cache',
        'Connection': 'keep-alive'
    });
    res.write('\n');

    (function(clientId) {
        clients[clientId] = res;

        req.on('close', function() {
            console.log('close');
            delete clients[clientId];
        });

    })(++clientId);
});

API code is working, I see 'start' in API's log when method /api/xyz is called by client.

Client (proxy HTTP requests to API):

app.use('/api', function(req, res) {

    req.on('close', function() {
        console.log('close');
    });

    var url = "http://localhost:8080/api" + req.url;
    req.pipe(request(url)).pipe(res);
});

Client code works also well. When browser tab is closed, I see 'close' in client app's log.

How ever, the problem is that when I close browser tab I don't see 'close' in API's log. Connection is never closed on API because close event is never detected at API's side.

Does anyone know why?

0

There are 0 answers