环境:polyv上传插件,生产环境上传失败,测试环境成功
问题代码:
main.js生产环境中运行了mockXHR方法
import { mockXHR } from '../mock'
if (process.env.NODE_ENV === 'production') {
mockXHR()
}
export function mockXHR() {
// mock patch
// https://github.com/nuysoft/Mock/issues/300
Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
Mock.XHR.prototype.send = function() {
if (this.custom.xhr) {
this.custom.xhr.withCredentials = this.withCredentials || false
if (this.responseType) {
this.custom.xhr.responseType = this.responseType
}
}
this.proxy_send(...arguments)
}
function XHR2ExpressReqWrap(respond) {
return function(options) {
let result = null
if (respond instanceof Function) {
const { body, type, url } = options
// https://expressjs.com/en/4x/api.html#req
result = respond({
method: type,
body: JSON.parse(body),
query: param2Obj(url)
})
} else {
result = respond
}
return Mock.mock(result)
}
}
for (const i of mocks) {
Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
}
}
问题原因:mockXHR执行后,XHR请求来会被拦截,使用内部MockXMLHttpRequest来替代原生的XMLHttpRequest,原生XMLHttpRequest已被覆盖,
load成功后,得到返回值是buffer,需要进行解析,responseType需要是'arrayBuffer'类型,但是mockXHR方法中
没有把responseType进行设置,而是设置成了空值。因此无法解析成功。
解决办法:判断只在开发环境使用,生产弃用