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) 
4
  • 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 give s a few promising results) Commented Mar 7, 2016 at 14:28
  • Possible duplicate of Express gzip static content, but I'm not 100% sure Commented Mar 7, 2016 at 14:35
  • Possible duplicate of Nodejs send data in gzip using zlib Commented Mar 7, 2016 at 14:37
  • must try to search before, hope here is answer stackoverflow.com/questions/14778239/… Commented Mar 7, 2016 at 14:38

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Yw, glad I could help.
but what if you pre-compressed the files (e.g. with webpack). I'm having the same issue where express does not like it if I set the content encoding header to gzip
Need more info here. This will blow up internet explorer 11 after node 12. Need compression to use gzip not deflate with that.
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) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.