2022年1月25日星期二

js fetch 新浪股票接口中文乱码解决方法

乱码问题
在 React 中使用 fetch 获取新浪股票接口数据时,出现乱码,代码如下:

fetch("/api/list=sz002307", { // 相当于 http://hq.sinajs.cn/list=sz002307
}).then( 
res => res.text()
).then(
    data => console.log(data);
)  

控制台输出为:

var hq_str_sz002307="����·��,4.730, ... 
1

原因分析
fetch 到的内容使用的是 GBK 编码,编码不一致导致中文乱码问题。


解决方法
fetch("/api/list=sz002307", {
}).then(
     res => res.blob()
).then(
     (data) => {
         let reader = new FileReader();
         reader.onload = () => {
             var text = reader.result;
             console.log(text);
         }
         reader.readAsText(data, 'GBK');
     }
)  

控制台输出:

var hq_str_sz002307="北新路桥,4.730, ...

问题解决

没有评论:

发表评论