android - 在本地主机上 react native android 连接后端服务

标签 android react-native fetch

我有一个由 Nodejs 处理的注册服务。该服务在 3001 端口上工作。我尝试从 React Native 应用程序连接此服务。但总是返回

ReactNativeJS: [TypeError: Network request failed]

我的组件和 package.json 代码如下。另外,我将 URL localhost 替换为 127.0.0.1,但它不起作用。当我从 Postman 测试后端服务时,它工作正常。给出非常常见的网络错误异常,因此很难理解问题的根源。每个 React Native 开发初学者都可以轻松面对这个问题。那么问题是由 React Native 还是 Android 引起的?

import React, { Component } from 'react';
import {
    TextInput,
    ScrollView,
    Alert,
    TouchableHighlight,
    Text,
    StyleSheet
} from 'react-native';

export default class Register extends Component {
    constructor(props) {
        super(props);
        this.onPress = this.onPress.bind(this);
    }

componentDidMount() {
    this.state = {
        email: '',
        password: '',
        passwordRepetition: '',
        error: '',
        loading: false
    };
}

onPress() {
    fetch('http://127.0.0.1:3001/user/register', {
        method: 'POST',
        headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            email: this.state.email,
            password: this.state.password,
        }),
    }).then(res => {
        console.log(res);
    })
        .catch(err => {
            console.log(err);
        });
}

render() {
    return (
        <ScrollView>
            <TextInput
                style={{ height: 40 }}
                placeholder="type@email.com"
                onChangeText={email => this.setState({ email })}
            />
            <TextInput
                style={{ height: 40 }}
                placeholder="veryhardpassword"
                secureTextEntry
                onChangeText={password => this.setState({ password })}
            />
            <TextInput
                style={{ height: 40 }}
                placeholder="repetition of password"
                secureTextEntry
                onChangeText={passwordRepetition =>
                    this.setState({ passwordRepetition })
                }
            />
            <TouchableHighlight style={styles.button} onPress={this.onPress}>
                <Text> Touch Here </Text>
            </TouchableHighlight>
        </ScrollView>
    );
}
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        paddingHorizontal: 10
    },
    button: {
        alignItems: 'center',
        backgroundColor: '#DDDDDD',
        padding: 10
    },
    countContainer: {
        alignItems: 'center',
        padding: 10
    },
    countText: {
        color: '#FF00FF'
    }
});

包.json

{
  "name": "mobile",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "react": "16.3.0-alpha.1",
    "react-native": "^0.54.0"
  },
  "devDependencies": {
    "babel-jest": "22.4.1",
    "babel-preset-react-native": "4.0.0",
    "eslint": "^4.18.2",
    "eslint-plugin-react": "^7.7.0",
    "jest": "22.4.2",
    "react-test-renderer": "16.3.0-alpha.1"
  },
  "jest": {
    "preset": "react-native"
  }
}

最佳答案

可能有 2 个案例来测试这个问题。

  1. 使用设备
  2. 使用模拟器

关键点在命令下运行

$adb reverse tcp:3001 tcp:3001

TEMPLATE: adb reverse tcp:{APPLICATIONPORT} tcp:{APPLICATIONPORT}

第一种情况是在 pc 中进行 ipconfig 并找到本地 IP 地址,如 192.168.1.4。你的网址应该是 http://192.168.1.4:3001/user/register

如果您使用模拟器,您应该使用以下 url,如 http://10.0.2.2:3001/user/register

在运行 adb reverse 命令后,这些 URL 对我有用。

关于android - 在本地主机上 react native android 连接后端服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49206456/

相关文章:

android - 我的应用程序在 Android 10 上运行良好,但在所有其他 Android 版本上崩溃。在模拟器和真实设备上

android - 共享偏好保存

android - 使用 zip 时保持一些文件未压缩

react-native - 如何删除覆盖导航 5.x 警告

ios - 架构 arm64 的 undefined symbol - JSClassCreate

ios - AppCenter react 原生 ios 构建失败 "usr/bin/xcodebuild failed with return code: 65 "

php - 使用 codeigniter 从 2 个表中获取数据

php - 图像不使用路径从数据库获取

android - 如何在选定的特定项目下方显示列表?

ios - 如何在parse中用includeKey查询 "Or "?