> 文章列表 > js读取fetch的返回值

js读取fetch的返回值

js读取fetch的返回值

需要注意,在ky里,400 500这种都是算catch error会走到的了。

有两种方式。

一种是硬解析,一种是使用ky,可以捕获到error异常,

error类型的:

(1)先捕获error,一般的话会有error.message , 但是这个message不一定能捕获的到东西;

(2)从网络中捕获到的error会有response,那么response.status应该就是http状态码,

此时进行打印,你会发现response的body是

readable stream,而且还locked:true,那么就是它只能被读取一次,

那么就clone一下,此外还要转换成arrayBuffer才可读

而且必须加上then才能拿到结果,因为即使转换成arrayBuffer也是一个promise

然后在then里 使用arrayBufferToString, 然后这时候是一个完全的字符串再 解析一下,这样就能读到文字的内容了

if (e?.response?.status == "404") {const res = e?.responselet copyRes = res.clone().arrayBuffer()copyRes.then((res: any) => {const response = JSON.parse(arrayBufferToString(res))if (response.errorCode === aaaaaaa) {status: "aaaaaaaaa",}
})

还有一个方法

用bodyreader,这个可能读到的工作量会比较大,不清楚具体场景

}).then((response) => response.body).then((body) => {console.log(body, '11111body')const reader =  body.getReader();reader.read().then(({ done, value }) => {if (done) { console.log('done'); } else { console.log('value', value); // 使用TextDecodervar enc = new TextDecoder("utf-8");var uint8_msg = new Uint8Array(value);console.log(enc.decode(uint8_msg), '11111');}})checkStatus(response);})