电容器 Android 未加载 http javascript 源

Capacitor Android not loading http javascript source

我正在尝试从 http://127.0.0.1:4002/

url 下的本地 Web 服务器加载远程脚本/css

但是电容器 android 似乎有错误,电容器 ios 工作正常。 我也成功地加载了 css https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap-grid.min.css

我的猜测是不支持http?

这是我加载它的代码

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap-grid.min.css" />
        <link href="http://127.0.0.1:4002/test/fonts.css" rel="stylesheet" />
        <meta charset="utf-8" />
        <meta
            name="viewport"
            content="initial-scale=1, maximum-scale=1.0, minimum-scale=1.0, width=device-width, height=device-height, viewport-fit=cover,  user-scalable=no"
        />
        <title>My Title</title>
    </head>

    <body id="body">
        
    </body>
</html>

这是我在 'chrome://inspect/#devices' 下遇到的错误

我的依赖项:

"@capacitor-community/http": "^1.0.0-alpha.1",
"@capacitor/android": "^3.0.0-rc.0",
"@capacitor/cli": "^3.0.0-rc.0",
"@capacitor/core": "^3.0.0-rc.0",
"@capacitor/device": "^0.5.5",
"@capacitor/dialog": "^0.4.5",
"@capacitor/filesystem": "^0.5.1",
"@capacitor/ios": "^3.0.0-rc.0",

我的capacitor.config.json

{
    "appId": "com.example.app",
    "appName": "hello-cap-2",
    "bundledWebRuntime": false,
    "npmClient": "npm",
    "webDir": "www",
    "plugins": {
        "SplashScreen": {
            "launchShowDuration": 0
        }
    },
    "server": {
        "allowNavigation": ["*"]
    },
    "android": {
        "allowMixedContent": true
    },
    "cordova": {}
}

得到答案于 https://github.com/ionic-team/capacitor/discussions/4477

127.0.0.1 is your computer, iOS simulator understand it because the simulator is running on your computer, but on Android, the emulator is a "virtual machine" with its own networking, so 127.0.0.1 for it its the own emulator, not your computer.

You can enable port forwarding to send the 4002 port traffic to the emulator, or you can use 10.0.2.2 IP as it automatically loops to 127.0.0.1

https://developer.android.com/studio/run/emulator-networking

Also, note that using 127.0.0.1 won't work on real devices because of the same reason, it's better if you use the local IP of the computer instead, something like 192.168.1.30