[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的数据重新转为想要的格式,按照上述方式转化,下载文件恢复正常

相关推荐
x-cmd13 小时前
[250512] Node.js 24 发布:ClangCL 构建,升级 V8 引擎、集成 npm 11
前端·javascript·windows·npm·node.js
Johnstons1 天前
AnaTraf:深度解析网络性能分析(NPM)
前端·网络·安全·web安全·npm·网络流量监控·网络流量分析
极小狐1 天前
极狐GitLab 容器镜像仓库功能介绍
java·前端·数据库·npm·gitlab
七冬与小糖3 天前
【本地搭建npm私服】使用Verdaccio
前端·npm·node.js
从味书3 天前
安装typescript时,npm install -g typescript报错
javascript·typescript·npm
亦世凡华、3 天前
前端npm包发布流程:从准备到上线的完整指南
前端·经验分享·npm·node.js·npm发包
巴巴_羊3 天前
yarn npm pnpm
前端·npm·node.js
Lysun0014 天前
(pnpm)引入 其他依赖失败,例如‘@element-plus/icons-vue‘失败
前端·javascript·npm·pnpm
MINO吖6 天前
项目改 pnpm 并使用 Monorepo 发布至 npm 上
前端·npm·node.js
极小狐7 天前
如何使用极狐GitLab 软件包仓库功能托管 npm?
java·前端·数据库·ci/cd·npm·gitlab·devops