【前端神奇bug记录单.1】通过axios下载的文件,无法打开

401 阅读1分钟

mock.js会修改responseType导致下载文件格式错误

前天对接新需求最后一个导出接口时出了一些问题。因新增了查询条件,且查询条件比较复杂(对象数组),于是把get请求换成post了,之前是直接把url塞a标签里进行下载。换了之后自测发现文件能下载,但无法打开。而swagger上测试是正常的,所以问题基本可以确定出在前端。各种方法试了无数次,甚至在群里喊了一个大佬来远程俩小时,依然没找到问题。

不过发现两个不对劲的地方:

  1. config里responseType是blob,但是request里的responseType是空的。 image.png

  2. 获取到的返回数据是string格式的 image.png

image.png

后续喊我们leader帮忙看,他看了一上午本来都考虑让后端换实现方式了,然后查到有相关博客说mock会影响文件下载。

取消引入mock,自测恢复正常。 查看mock源码,果然有重置responseType的代码,这波排查了接近一天,结果注释一行代码解决 - _ -

// 初始化 Response 相关的属性和方法
Util.extend(MockXMLHttpRequest.prototype, {
   responseURL: '',
   status: MockXMLHttpRequest.UNSENT,
   statusText: '',
   // https://xhr.spec.whatwg.org/#the-getresponseheader()-method
   getResponseHeader: function(name) {
       // 原生 XHR
       if (!this.match) {
           return this.custom.xhr.getResponseHeader(name)
       }

       // 拦截 XHR
       return this.custom.responseHeaders[name.toLowerCase()]
   },
   // https://xhr.spec.whatwg.org/#the-getallresponseheaders()-method
   // http://www.utf8-chartable.de/
   getAllResponseHeaders: function() {
       // 原生 XHR
       if (!this.match) {
           return this.custom.xhr.getAllResponseHeaders()
       }

       // 拦截 XHR
       var responseHeaders = this.custom.responseHeaders
       var headers = ''
       for (var h in responseHeaders) {
           if (!responseHeaders.hasOwnProperty(h)) continue
           headers += h + ': ' + responseHeaders[h] + '\r\n'
       }
       return headers
   },
   overrideMimeType: function( /*mime*/ ) {},
   responseType: '', // '', 'text', 'arraybuffer', 'blob', 'document', 'json'
   response: null,
   responseText: '',
   responseXML: null
})

碰到疑难杂症时,注意准确提炼关键词,实在不清楚原因时,多尝试几个关键词进行搜索,排查问题也要细致,这次前期的排查其实已经和答案很接近了。