Android 应用程序在连接到数据库时出现网络错误

时间:2021-07-09 16:11:10

标签: android database mongodb react-native android-studio

我有一个 React Native 应用程序,可以从数据库中获取书籍并显示它们。当 mongodb 后端运行时,它在 iOS 上运行良好,但在 android 上运行不正常。我刚刚收到如下所示的网络错误。

enter image description here

你们有没有人知道如何解决它? 这是我的 build.gradle:

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "29.0.2"
        minSdkVersion = 16
        compileSdkVersion = 29
        targetSdkVersion = 29
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath("com.android.tools.build:gradle:3.5.3")
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url("$rootDir/../node_modules/react-native/android")
        }
        maven {
            // Android JSC is installed from npm
            url("$rootDir/../node_modules/jsc-android/dist")
        }

        google()
        jcenter()
        maven { url 'https://www.jitpack.io' }
    }
}

这是我的 AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools">
    <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />s
    <uses-sdk android:targetSdkVersion="29" android:minSdkVersion="16" tools:overrideLibrary="com.facebook.react"/>
    <application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" />
</manifest>

请告诉我如何解决这个问题。 谢谢。

(如果您需要查看任何前端或后端文件,请在评论中告诉我。)

1 个答案:

答案 0 :(得分:0)

我解决了这个问题,并认为该解决方案可能对其他人有所帮助。发生的所有事情是模拟器没有获得本地主机。为了解决这个问题,在我的前端,我用 10.0.2.2:3000 替换了 localhost:3000。它解决了这个问题。

代替

.post('http://localhost:3000/login'...

应该是

.post('http://10.0.2.2:3000/login'...

感谢@Raghav Herugu 帮我解决问题