Search code examples
node.jsexpresscurlhttp-compression

express and compression, can't find what I make wrong :-(


I can't find why I can't compress my content. I tried many way but when I check with curl ( curl -I -H 'Accept-Encoding: gzip' http://localhost:8080/free.html ) on a static page or on basic local content ( / ) I can't find any way to compress my content

What did I made wrong ? Here is my code :

var express = require('express');
var compression =   require('compression');
var morgan =        require('morgan');
var favicon =       require('serve-favicon');

var app =           express();

app.use(compression({
    filter: function () { return true; }
}));
app.use(morgan('combined'));
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.static(__dirname + '/public'));



app.get('/', function(req, res) {
    res.setHeader('Content-Type', 'text/plain');
    res.end('Vous êtes à l\'accueil');
});
app.use(function(req, res){
    res.send(404);
});

app.listen(8080);

thanks

Gregoire


Solution

  • I haven't figured out why yet, but it appears that if the threshold isn't set low enough, it won't encode it. Here's an example:

    var express = require('express')
    var app = express()
    var compression = require('compression')
    
    app.use(compression({ threshold: 6 }))
    // app.use(express.static(__dirname + '/dist'))
    
    app.all("/*", function(req, res, next) {
      res.send('done')
    })
    
    var server = app.listen(8080)
    

    The docs state that 6 is the default. When I test this:

    $ curl -i -H 'Accept-Encoding: gzip' http://localhost:8080
    

    The Content-Encoding header is not set. When I set it to a threshold 4 or lower, it then responds with encoded content:

    HTTP/1.1 200 OK
    X-Powered-By: Express
    Content-Type: text/html; charset=utf-8
    Vary: Accept-Encoding
    Content-Encoding: gzip   // <——————————
    Date: Mon, 06 Feb 2017 20:23:24 GMT
    Connection: keep-alive
    Transfer-Encoding: chunked
    
    K??K??-⏎