我正在尝试通过 Capacitor 编写一个使用 PouchDB 的移动应用程序。当我通过 Android Studio 在模拟器中运行应用程序时,与远程 CouchDB 实例的连接失败。我已追踪到此问题是由于在 Android 上运行时某些 URL 的
fetch
API 出现故障。
为了调试,我制作了一个最小的 Web 应用程序,并使用 Capacitor 封装它以在 Android 上运行。该应用程序包含以下代码
const testFetch = (url) => {
console.log("Testing fetch", url)
fetch(url)
.then((response) => response.text())
.then((t) => {
console.log("Respose from fetch:", url)
console.log(t)
console.log("that was it")
})
.catch((reason) => {
console.log("FETCH FAILED", url, reason)
})
}
然后我进行了三个测试:
testFetch("https://jsonplaceholder.typicode.com/todos/1"); // just some JSON
testFetch("http://10.0.2.2:5984/simple"); // local pouchdb instance
testFetch("http://10.0.2.2:8080/sample.json"); // local http server + CORS
后两个使用的 IP 地址是在 Android 模拟器中运行时开发计算机的别名。我确认我可以从模拟器上的浏览器访问所有这些 URL,但应用程序在第一个 URL 上成功,在后两个 URL 上失败(错误:
TypeError: Failed to fetch
)。在浏览器中运行基本 Web 应用程序时,一切都会成功(使用 localhost 而不是 10.0.2.2)。
CORS 标头位于所有 URL 上。据我所知,该应用程序甚至没有尝试访问失败的两个服务器 - 例如没有 HEAD 请求。我还尝试了各种其他 URL,但看不到失败的模式 - 例如。这不是端口号!= 80.
任何有关正在发生的事情的线索将不胜感激。
对于那些遇到同样问题的人(使用 Ionic、Capacitor、Android 等)。我通过做两件事成功地做到了这一点:
添加:
android: { allowMixedContent: true }
到电容器.config.ts
并添加:
android:usesCleartextTraffic="true"
在AndroidManifest.xml中
(强制XKCD:https://xkcd.com/979/)