[mockjs]Mock使用过程中的坑

[mockjs]Mock使用过程中的坑

现象描述

mockjs在使用的过程中出现了下载文件无法正常打开的问题,但是在线上环境是正常的

console.log打印返回的response,发现是本地无法正常解析response.data

在代码中,该请求设置了responseType:blob,所以正常情况下接收的response.data应该是blob类型

ts 复制代码
data: Blob{size: 4608,type: "application/vnd.ms-excel"}

在使用了 mockjs 的情况下,接收到的response.data不是文件流,而是string类型

data: '��\x11ࡱ\x1A�\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00;\x00\x03\x00��\t\x00\x06\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00...\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00',

原因分析

两者的区别是线上环境是没有使用mockjs的

mockjs源码中responseType的值被覆盖了,导致mockjs开启的情况下,调用真实接口responseType无法使用设置的值

解决方案

修改源码

 this.custom.xhr.responseType = this.responseType //复制原始XHR的responseType
 this.custom.xhr.send(data)//源代码

该方式是直接对mockjs中/src/mock/xhr/xhr.js文件进行修改,但是该方式只有原作者修改并上传才不会影响下次的使用,否则更改的是本地的,对于每次初始化时重新下载了mockjs无法从根本上解决

处理无法识别的文件流

mockjs源码导致了文件流被responseType:'json'解析了,因此无法正确识别,因此,我们只需在将转换为json的response.data重新转换为需要的类型。

例如 arrayBuffer,可以对接收到的res.data:

ts 复制代码
new Uint8Array(res.data)

例如 blob ,可以对接收到的res.data:

ts 复制代码
const blob=new Blob([JSON.stringify(res.data)], { type: "application/json" })

mockjs 引用导致responseType:"blob"被重写为json了,因此需要把转成json的数据重新转为想要的格式,按照上述方式转化,下载文件恢复正常

相关推荐
影子落人间2 分钟前
已解决npm ERR! request to https://registry.npm.taobao.org/@vant%2farea-data failed
前端·npm·node.js
又写了一天BUG3 小时前
npm install安装缓慢及npm更换源
前端·npm·node.js
森叶4 小时前
Electron-vue asar 局部打包优化处理方案——绕开每次npm run build 超级慢的打包问题
vue.js·electron·npm
chen序员20 小时前
如何切换淘宝最新镜像源(npm)【2024版】
npm
FakeOccupational1 天前
nodejs 007:错误npm error Error: EPERM: operation not permitted, symlink
前端·npm·node.js
亦舒.1 天前
JSDelivr & NPM CDN 国内加速节点
前端·npm·node.js
代码搬运媛1 天前
code eintegrity npm err sha512
前端·npm·node.js
猿来如此呀1 天前
运行npm install 时,卡在sill idealTree buildDeps没有反应
前端·npm·node.js
hw_happy1 天前
解决 npm ERR! node-sass 和 gyp ERR! node-gyp 报错问题
前端·npm·sass
程序员小羊!2 天前
切换淘宝最新镜像源npm详细讲解
前端·npm·node.js