[mockjs]Mock使用过程中的坑

mockjsMock使用过程中的坑

现象描述

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

相关推荐
江屿风3 天前
【Plain Language Large Model】【从浏览器到全栈:一课精通Node.js三剑客】流食般投喂
笔记·前端框架·npm·node.js·js·npx
少年的范儿5 天前
Windows 安装 Node.js 教程:nvm 版本管理 + pnpm 安装配置
windows·npm·node.js
peach5 天前
同样是装依赖,为什么 npm 长成 node_modules,Maven 长成 .m2
npm·node.js·maven
chunyublog7 天前
HDFS 上传文件名空格问题排障教程
前端·javascript·npm
MasonYyp8 天前
安装npm依赖仓库Verdaccio
前端·npm·node.js
jiangliushi69 天前
GPT-6.1 Sol 免费用:PowerShell 装 Codex 报“禁止运行脚本 npm.ps1”?一条命令解决
前端·gpt·npm
Elcker10 天前
YnuoAgent(依诺):一个 npm 包,跑起属于自己的 AI 研发平台
前端·人工智能·npm
Patrick_Wilson13 天前
悬浮提示从哪来:LSP、tsserver 与 .d.ts
typescript·npm·前端工程化
Patrick_Wilson13 天前
npm 的 bin 如何接到 npm run 与 npx
npm·node.js·前端工程化
Patrick_Wilson13 天前
import 之后发生了什么:package.json、解析与安装产物
npm·node.js·前端工程化