反H5代码打包成apk时遇到报错:Fetch API cannot load file:///a_asset/xxx.json. URL scheme "file" is not support。
原因是js里调用了fetch方法,而fetch api不支持file:///。 以下是fetch方法的替换文案:
function fetchLocal(url, data) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest
xhr.onload = function() {
resolve(new Response(xhr.responseText, {status: xhr.status}))
}
xhr.onerror = function() {
reject(new TypeError('Local request failed'))
}
xhr.open('GET', url)
xhr.send(data)
})
}
如果是 arraybuffer, 则如下:
function fetchLocal(url) {
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest
xhr.onload = function () {
resolve(new Response(xhr.response, { status: xhr.status }))
}
xhr.onerror = function () {
reject(new TypeError('Local request failed'))
}
xhr.open('GET', url)
xhr.responseType = "arraybuffer";
xhr.send(null)
})
};
还遇到另一个报错:Unable to open asset URL: file:///android_asset/www/
我遇到的原因是目录名称里有下划线,去掉下划线就可以了。
2337

被折叠的 条评论
为什么被折叠?



