mockjs 导致responseType设置无效,影响blob文件下载的解决方案

   最近一个做的项目需要用到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)

  }

})()




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值