Please have a look at my code where I'm trying to compress data using connect.compress middleware. How can I parse JSON string in browser to get the decompressed data. When I try to hit localhost:2080 I'm getting Page loading error.
Client code
var options = {
host: '127.0.0.1',
port: 2080,
path: "/",
headers:{
'accept-encoding': 'gzip'
}
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function (chunk) {
var data2 = JSON.parse(data);
console.log(data2.app_id);
});
});
Server Code
app = connect();
app.use(connect.compress(console.log("compressed data")))
app.use(connectDomain())
.use(connect.query())
.use(connectRoute(function (router) {
router.get('/', function (req, res) {
var acceptEncoding = req.headers['accept-encoding'];
if (acceptEncoding.match(/\bdeflate\b/)) {
res.setHeader('content-encoding', 'deflate');
} else if (acceptEncoding.match(/\bgzip\b/)) {
res.setHeader('content-encoding', 'gzip');
}
console.log(res._headers);
res.setHeader('Content-Type', 'application/json');
res.end('{"app_id": "A3000990"}');
})
}))
.use(function(err, req, res, next) {
res.end(err.message);
});
http.createServer(app).listen(2080);
We can't control the browser. It either sends the Accept-encoding: gzip, deflate header or it doesn't. So can we get compress data using connect.compress().
Any help will be really helpful
Thanks
There's a couple of issues here:
Content-Encoding headers in the server, but also use connect.compress which will also set that header. That could create conflicts, so don't add those headers yourself and let connect.compress handle all the compression;req.end() to it;