跳转至

解决Fetch获取中文乱码的问题

最近使用fetch时,根据返回的内容中包含有中文时出现了乱码的情况。

fetch("https://www.poxiao.com")
    .then(response => response.text())
    .then(str => (new window.DOMParser()).parseFromString(str, "text/html"))
    .then(htmlData=>{
        console.log(htmlData);
    })
一般来说,使用以上代码能获取到html内容,但是中文部分却出现了乱码,如图:

网上搜索一番,总算是解决了问题:fetch返回blob数据,然后使用reader对blob做处理。代码如下:
fetch("https://www.poxiao.com/")
    .then(response=>response.blob())
    .then(blob=>{
        var reader = new FileReader();
        reader.onload = function(e) {
            var htmlData = reader.result;
            htmlData=(new window.DOMParser()).parseFromString(htmlData,"text/html");
            console.log(htmlData);
        }
        reader.readAsText(blob, 'GBK') 
    })
效果如下: