Fetch获取内容乱码问题
使用 Fetch 获取 gbk 编码的网页时,发现返回的内容乱码了
fetch("url").then(res => res.text()).then(text => console.log(text));
添加 charset 请求头也未能解决问题:
const headers = new Headers();
headers.append("Content-Type", "text/plain; charset=gbk");fetch("url", headers).then(res => res.text()).then(text => console.log(text));
查看了文档,原来是 Response.text() 方法始终会以 UTF-8 来进行解码。
我们可以通过 TextDecoder 来使用特定编码格式进行解码:
fetch("url").then(res => res.arrayBuffer()).then(buffer => {const decoder = new TextDecoder("gbk");const text = decoder.decode(buffer);console.log(text);});