fetch将返回值进行对应类型的转换

const myInit = {
      method: 'GET',
      mode: 'same-origin',
      credentials: 'same-origin',
      cache: 'default'
};
    
fetch(url, myInit).then(res => {
    const contentType = res.headers.get("Content-Type");
    // 根据返回contentType,处理是json,还是下载文件
    if (contentType.toLowerCase() == "application/json;charset=utf-8") {
      res.json().then(data => {
          alert(data.success);
      });
    } else if (contentType.toLowerCase() == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") {
      res.blob().then(blob => {
          // 创建一个a标签,用于下载
          var a = document.createElement('a');
          var url = window.URL.createObjectURL(blob);
          var fileName = '被下载的文件.txt';
          a.href = url;
          a.download = fileName;
          a.click();
          window.URL.revokeObjectURL(url);
      });
    }
});

你可能感兴趣的:(fetch将返回值进行对应类型的转换)