0

I am trying to handle gzip.

My sources: zlib,compression,https(article by Rob W)

Server-Side:

    app.get('*', function (req, res, next) {
    if (req.headers['x-forwarded-proto'] != 'https') {
        res.setHeader('Content-Type', 'text/event-stream')
        res.setHeader('Cache-Control', 'no-cache')

        // send a ping approx every 2 seconds
        var timer = setInterval(function () {
            res.write('data: ping\n\n')

            // !!! this is the important part
            res.flush()
        }, 2000)

        res.on('close', function () {
            clearInterval(timer)
        })

        res.redirect('https://...herokuapp.com' + req.url)//req.connection.remoteAddress
    }
    else {
        next();
    }
})

Error:

events.js:85 throw er; // Unhandled 'error' event ^ Error: write after end at ServerResponse.OutgoingMessage.write (_http_outgoing.js:413:15) at ServerResponse.res.write (...\index.js:80:17) at null. (...\app.js:63:17) at wrapper [as _onTimeout] (timers.js:265:14) at Timer.listOnTimeout (timers.js:110:15)

Process finished with exit code 1

Client side request:

<link rel="stylesheet" type="text/css" href="../.../.../....min.css.gz">
Community
  • 1
  • 1
user254197
  • 883
  • 2
  • 9
  • 31

1 Answers1

0

You can't res.write() after res.redirect(). The latter ends the response.

You might consider creating a dedicated route for your Server-Sent Events stream instead.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Can you give me some good links for dedicated routes on express.js/node.js ? You mean something like that in my app.js i use app.use('/',site) and in my route site.js I use router.get('/' ... ? – user254197 Aug 29 '15 at 07:35
  • I mean creating a dedicated route like `/stream` or similar that always responds with a Server-Sent Events stream and does nothing else. You will probably want to store the response object somewhere so that you can reference it from other scopes when you need to send a message to a particular connected user. – mscdex Aug 29 '15 at 07:40