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

使用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);
}
原文地址:https://www.cnblogs.com/confucius-dream-zhougong/p/12166250.html