1

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)
  • You are correctly setting the `Content-Encoding: gzip` header, but you are nor correctly serving gzip'ed content (i.e., `hello world` is not a valid output for the gzip algorithm). This isn't an answer because I'm not sure how to resolve it (although searching for [`express gzip`](https://encrypted.google.com/#q=express+gzip) give s a few promising results) – apsillers Mar 07 '16 at 14:28
  • Possible duplicate of [Express gzip static content](http://stackoverflow.com/questions/6370478/express-gzip-static-content), but I'm not 100% sure – apsillers Mar 07 '16 at 14:35
  • Possible duplicate of [Nodejs send data in gzip using zlib](http://stackoverflow.com/questions/14778239/nodejs-send-data-in-gzip-using-zlib) – Zeeshan Hassan Memon Mar 07 '16 at 14:37
  • must try to search before, hope here is answer http://stackoverflow.com/questions/14778239/nodejs-send-data-in-gzip-using-zlib – Zeeshan Hassan Memon Mar 07 '16 at 14:38

2 Answers2

2

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.

therebelcoder
  • 929
  • 11
  • 28
2

The problem with your code is that you are trying to send the plain text and tell the browser to expect for gzipped content.

Below code would be helpful for kick-starting with gzip encoding:

var zlib = require('zlib');
app.get('/', function(req, res){
   res.setHeader('Content-Encoding', 'gzip')
   res.setHeader('Content-Type', 'text/plain')
   var text = "Hello World!";
   var buf = new Buffer(text, 'utf-8'); 
   zlib.gzip(buf, function(_, result) { 
      res.send(result); 
   });
});
app.listen(3001)