Node.js https.get()不';t返回UTF-8字符
我无法从xml文件中获取土耳其语字符。即使我将编码设置为utf-8,它们也似乎是问号Node.js https.get()不';t返回UTF-8字符,node.js,xml,https,Node.js,Xml,Https,我无法从xml文件中获取土耳其语字符。即使我将编码设置为utf-8,它们也似乎是问号 https.get("https://clients1.google.com/complete/search?hl=tr&output=toolbar&q=mustafa kemal", (res) => { res.setEncoding("utf-8"); var body = ''; res.on('data',
https.get("https://clients1.google.com/complete/search?hl=tr&output=toolbar&q=mustafa kemal", (res) => {
res.setEncoding("utf-8");
var body = '';
res.on('data', (d) => {
body += d;
})
res.on('end', function(){
console.log(body);
})
})
问题在于响应内容类型不在
utf8
中,而是ISO-8859-9
要检查该选项,请执行以下操作:
console.log(res.headers);
{
date: 'Sat, 07 Jul 2018 17:02:46 GMT',
expires: 'Sat, 07 Jul 2018 17:02:46 GMT',
'cache-control': 'private, max-age=3600',
'content-type': 'text/xml; charset=ISO-8859-9',
p3p: 'CP="This is not a P3P policy! See g.co/p3phelp for more info."',
server: 'gws',
'x-xss-protection': '1; mode=block',
'x-frame-options': 'SAMEORIGIN'
}
因此,如果您这样做:res.setEncoding('binary')代码>它可以正常工作
如果发送用户代理
标题,该请求将返回utf8
,而不是ISO-8859-9
const options = {
hostname: 'clients1.google.com',
path: '/complete/search?hl=tr&output=toolbar&q=mustafa+kemal',
method: 'GET',
headers: {
'User-Agent': 'Mozilla/5.0'
}
};
https.get(options, (res) => {
res.setEncoding('utf8');
var body = '';
res.on('data', (d) => {
body += d;
})
res.on('end', function() {
console.log(body);
})
});
因此,总之,您应该检查响应中的内容类型
标题,并设置一种编码或另一种编码