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

来源:互联网 发布:java向构造方法里传参 编辑:程序博客网 时间:2024/06/11 12:50
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);      });    }});
阅读全文
0 0