如果json内容失败,能够获取response对象的文本内容

问题描述 投票:0回答:1

json解码失败是否可以获取到response的文本值?

我有以下代码:

try {
   var response = await fetch(url, options);
   var data = await response.json();
   // do stuff
}
catch(error) {
   var text = await response.text(); // TypeError: Failed to execute 'text' on 'Response': body stream already read
}

如果服务器关闭或网络离线,有时会发生这种情况。

我意识到这使得

response.json()
函数毫无用处,因为如果我有错误,我总是需要获取文本值。

目前错误是:

SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

忽略上面的错误,请告诉我是否有办法在我致电

json()
后从响应中获取文本值。

在我看来,如果使用

response.json()
方法将响应转换为 json 的方法失败,它应该允许您获取文本值。这有道理吗?

更新
根据建议,我测试了检查响应中的内容类型标头,它包含 application/json

response.headers.get("content-type");
'application/json; charset=utf-8'

这应该适用于我的用例。

javascript json fetch-api
1个回答
0
投票

这是一个等待和异步答案,使用此处链接的另一个问题的代码,在调用

response.json()
之前首先检查内容类型。没有克隆响应。

async function myFetch(myRequest) {

  try {
    const response = await fetch(myRequest);
    const contentType = response.headers.get("content-type");
    var data;
    if (contentType && contentType.includes("application/json")) {
       data = await response.json(); 
    }
    else {
       data = await response.text();
    }

    return data;
  }
  catch(error) {
    // other errors occurred
    throw error;
  }
}

try {
   var json = await myFetch("test");
   if (json && json.success) { 
      // do something
   }
}
catch(error) {

}

另一个如果不是 json 则抛出错误的示例(未测试):

async function myFetch(myRequest) {
  try {
    const response = await fetch(myRequest);
    const contentType = response.headers.get("content-type");
    var data;
    if (contentType && contentType.includes("application/json")) {
       data = await response.json();
       return data;
    }
    throw new Error(response);
  }
  catch(error) {
    throw error;
  }
}

// use
try {
   var json = await myFetch("test");
}
catch(error|response) {
   if (error instanceof Error) {}
   if (error instanceof Response) {}
}
© www.soinside.com 2019 - 2024. All rights reserved.