使用fetch进行数据请求时报json错误

我与影子孤独终老i 提交于 2020-01-08 15:24:02

使用fetch进行数据请求返回response对象,response.json报错。原因是response中含有特殊字符。

fetch(url).then(response => response.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e))

取消response.json()调用,使用response.text()返回请求数据的字符串,对特殊字符进行转义替换处理后,再进行json对象化传入请求成功的回调函数中。transSpecialChar是对字符串处理的函数

interface Body {
    readonly body: ReadableStream<Uint8Array> | null;
    readonly bodyUsed: boolean;
    arrayBuffer(): Promise<ArrayBuffer>;
    blob(): Promise<Blob>;
    formData(): Promise<FormData>;
    json(): Promise<any>;
    text(): Promise<string>;
}
response.text().then((text) => {
    const json = JSON.parse(this.transSpecialChar(text));
    successCallBack(json);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!