问题
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
回答1:
There's a couple of issues here:
- you're setting
Content-Encoding
headers in the server, but also useconnect.compress
which will also set that header. That could create conflicts, so don't add those headers yourself and letconnect.compress
handle all the compression; - you don't actually send the HTTP request in your client, add
req.end()
to it; - there's no attempt to decompress the compressed data in your client; how to do that can be found here;
来源:https://stackoverflow.com/questions/15496042/error-loading-webpage-while-parsing-json-string