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

相关推荐
LisEcho3 小时前
yoyoj-rn — RN 的脚手架工具可以不是 @react-native-community/cli
前端·react native·npm
醉风塘3 小时前
NPM:从“模块之痛”到“生态之基”的演化史
前端·npm·node.js
水冗水孚3 小时前
通俗易懂地谈谈,前端工程化之自定义脚手架的理解,并附上一个实践案例发布到npm上
javascript·npm·node.js
蚂蚁不吃土&4 小时前
cmd powershell svm nodejs npm
前端·npm·node.js
Lucky_Turtle2 天前
【Node】npm install报错npm error Cannot read properties of null (reading ‘matches‘)
前端·npm·node.js
水冗水孚2 天前
20张图的保姆级教程,记录使用Verdaccio在Ubuntu服务器上搭建Npm私服
npm
Irene19912 天前
npm 完整生命周期脚本及特点
npm·生命周期
登山者3 天前
npm发布报错急救手册:快速解决2FA与令牌问题
前端·npm
Asurplus3 天前
【VUE】15、安装包管理工具yarn
前端·vue.js·npm·node.js·yarn
fpl11163 天前
npm :无法加载文件 D:\...\nodejs\npm.ps1,因为在此系统上禁止运行脚本
前端·vscode·npm·node.js·命令模式