我正在尝试获取CSS样式表,由于某种原因,响应都是乱码。这是编码错误吗?响应头表示编码只是UTF-8。
var https = require('https');
var fs = require('fs');
var url ='https://d14pr3cu5atb0x.cloudfront.net/pkg/css/chimera-e6f0150f64.css';
var request = https.request(url, function (res) {
var data = '';
res.on('data', function (chunk) {
data += chunk;
});
res.on('end', function () {
console.log(data);
});
});
request.on('error', function (e) {
console.log(e.message);
});
request.end();
输出:
�{��6�7���zk+�8e�.�Ԟڱ�8�m�v�ٓrQ%1#�
�g�n:��|�쎈��Y�˗H�,-�"��?�(�f������:�]&Ep�.�h��_��'�t͓��,�+R�{w��Z�f
���-A���<n�E�ϫ8;N>9�ҢH�g�ps�%�uq����*�y��?�
�\��y�/WYz�-��4;��r����E=!�$<i}�$0�ZK��:�ǻ~*�;�/�˻A�I�kVC>Z�P�����Ԛ2��|�/�Qvy�e���L�Lf�Ye��Ul�e��U}1i�FȤHŃ���N������҆'()�*X���_���h.�#TG&7ς8�u���M�
Lq�ML6ZI:D���f$�Ԓ�%���y�<�]A�
&l6�M�A^�n�]�����A��V��]tX$i{��}��JE���b����ԯ�}LX�}R���0�^�6?U�����\4���:�����8hf�*����T�2�a;?E�&׳M��<�h�ӻ�Is'��e��"�o�v�#�^�E�l��2Yͣ}��;��!���4-⬽��L���ov� ]~�"xu{\$�~ݞ�6���Q��
�D��y�R�9�r7; t�k�"��n(h��h�ln�r4�y�%�;�xvlӏ�2�rdK;4-��jr���b��V��Y��-�m���W��D�Y��")6�o,c��yw�Z�?���b�c�U$E�I�w�&�g
�9��0
���6��H���Ռ�����Vx7O�]�$1��{E�m�Ksdw( �{�AN|2OYg�]|��-H�%��;T��z�q@R����:����HR���
答案 0 :(得分:1)
我从未使用过node.js,但对我而言,看起来数据是压缩的,并且基于此处的文档:https://www.npmjs.com/package/request看起来您需要启用gzip才能获得正确的响应。下面是文档设置gzip中示例的复制和粘贴,它会生成正确的数据:
var url ='https://d14pr3cu5atb0x.cloudfront.net/pkg/css/chimera-e6f0150f64.css';
var request = require('request')
request(
{ method: 'GET'
, uri: url
, gzip: true
}
, function (error, response, body) {
// body is the decompressed response body
console.log('server encoded the data as: ' + (response.headers['content-encoding'] || 'identity'))
console.log('the decoded data is: ' + body)
}
)
.on('data', function(data) {
// decompressed data as it is received
console.log('decoded chunk: ' + data)
})
.on('response', function(response) {
// unmodified http.IncomingMessage object
response.on('data', function(data) {
// compressed data as it is received
console.log('received ' + data.length + ' bytes of compressed data')
})
})