最近一个做的项目需要用到mockjs来生成模拟的数据,而别的模块涉及到文件下载,需要设置responseType为blob,由于mockjs会覆盖原生的xmlRequest导致responseType设置无效,引起下载错误的bug
常见的解决方法:
方法1:去掉mockjs,换别的方案(废话篇,我想大多数都是为了搜索解决方法的,而不是干掉产生问题的人),很显然这个方案不适合
方法2:第二个修改mockjs源码,这个如果公司有私库,自己内部使用完全没问题
方法3:重写mockjs的原型
在引入mockjs的地方,使用prototype修改Mockjs的原型方法,这样既可以保留mockjs,又不会因为别人下载依赖导致修改源码无效的问题
import Mock from "mockjs";
Mock.XHR.prototype.send = (() => {
const _send = Mock.XHR.prototype.send
return function () {
if (!this.match) {
this.custom.xhr.responseType = this.responseType || ''
this.custom.xhr.timeout = this.timeout || 0
this.custom.xhr.withCredentials = this.withCredentials || false
this.custom.xhr.onabort = this.onabort || null
this.custom.xhr.onerror = this.onerror || null
this.custom.xhr.onload = this.onload || null
this.custom.xhr.onloadend = this.onloadend || null
this.custom.xhr.onloadstart = this.onloadstart || null
this.custom.xhr.onprogress = this.onprogress || null
this.custom.xhr.onreadystatechange = this.onreadystatechange || null
this.custom.xhr.ontimeout = this.ontimeout || null
}
return _send.apply(this, arguments)
}
})()