在 Android nativescript 中发出不安全的 http 请求

Making non-secure http requests in Android nativescript

我正在尝试从 nativescript 向常规 http(而非 https)服务器发出 http 请求。

    let headers = new Headers();
    headers.append("Content-Type", "application/json");

    this.http.request(
        "http://localhost:3050/register", 
        {
            method: "POST",
            headers: headers,
            body: JSON.stringify({
                username: user.username,
                email: user.email,
                password: user.password
            })
        })

当向 https 服务器发出请求时,该请求工作完美,但当向 http 服务器(这是我当前 运行 所在的服务器)发出时,它不起作用。

在 iOS 中,我不得不在 info.plist 文件中添加以下内容以允许对 http 服务器的请求,之后它工作正常:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

但是,在 Android 中,请求仍然无法正常工作,而且我找不到任何关于为使请求在 http 服务器上工作而需要进行的更改的文档。请求甚至没有到达服务器。

感谢任何帮助。

谢谢。

Localhost 表示您 运行 所在的设备。使用 Android 时,您的环回地址不再是标准的 127.0.0.1 (a.k.a. localhost) 而是类似于10.0.2.2(它可能会有所不同,具体取决于您使用的是 AVD 还是 GenyMotion)

更多

你也可以跨平台解决方案

我从

修改了位于app\App_Resources\Android\src\mainAndroidManifest.xml
    <application
        android:name="com.tns.NativeScriptApplication"
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">

    <application
        android:name="com.tns.NativeScriptApplication"
        android:allowBackup="true"
        android:icon="@drawable/icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">

我添加了最后一行:android:usesCleartextTraffic="true"

然后成功了!

参见:https://www.nativescript.org/blog/secure-your-mobile-app-securing-data-in-transit