我想分析一个从http请求,显示错误,如果需要,然后返回数据.
这就是我现在正在做的事情:
fetch(URL,{method:"GET"})
.then(async response => { await read_errors(response) })
// .then(response => { read_errors(response) }) (Both had been tried)
.then( function(data) {
doSomething(data)
})
.catch( error => { display_error(error) })
使用此功能:
async function read_errors(response) {
const isJson = response.headers.get('content-type')?.includes('application/json');
const data = isJson ? await response.json() : null;
const isText = response.headers.get('content-type')?.includes('text/');
const text = isText ? await response.text() : null;
// check for error response
if (!response.ok) {
// get error message from body or default to response status
const error = (data && data.message) || text || response.status;
console.error("Something went wrong : ",error)
return Promise.reject(error);
} else {
fckng_response = isJson ? data : text
return Promise.resolve(fckng_response)
}
}
但我有TypeError: data is undefined
来自服务器的答案是正确的,头和数据都是正常的.
我做错了什么?