node.jsgruntjsgzipcontent-encoding

Need to add a header in response header with the key and value as "Content-Encoding" as "gzip"


I am trying to run the sample application with the customized header but when i try to run this application, it throws the error as "Content Encoding Error". I would like to add this custom header on my application to use the grunt-gzip compression. can anyone tell why this error comes and how to resolve it?

var express = require('express'); var app = express();

app.get('/', function(req, res){
  res.setHeader('Content-Encoding', 'gzip')
  res.send('hello world');
});

app.listen(3001)

Solution

  • The response header will just tell your client what kind of response to expect. To actually compress it, you need to tell Express to do so. Assuming you're using Express 4+, you need to install the package separately:

    npm install compression --save

    In your code:

    var compress = require("compression");

    Before app.get(), write: app.use(compress());

    Express will compress all responses now.