解析JSON字符串时加载网页时出错 [英] Error loading webpage while parsing JSON-string

查看:214
本文介绍了解析JSON字符串时加载网页时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请查看我尝试使用connect.compress中间件压缩数据的代码.如何在浏览器中解析JSON字符串以获取解压缩的数据.当我尝试访问localhost:2080时,出现页面加载错误.

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.

客户代码

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);
});
});

服务器代码

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);

我们无法控制浏览器.它要么发送Accept-encoding:gzip,deflate标头,要么不发送.这样我们就可以使用connect.compress()获得压缩数据了.

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

谢谢

推荐答案

这里有几个问题:

  • 您要在服务器中设置Content-Encoding标头,但也要使用connect.compress来设置标头.这可能会产生冲突,因此不要自己添加这些标头,而是让connect.compress处理所有压缩;
  • 您实际上并没有在客户端中发送HTTP请求,请向其中添加req.end()
  • 没有尝试对客户端中的压缩数据进行解压缩; 可以在此处找到;
  • you're setting 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;
  • 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;

这篇关于解析JSON字符串时加载网页时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆