在localhost上反应本机android连接后端服务

时间:2018-03-10 07:22:35

标签: android react-native fetch

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

  

ReactNativeJS:[TypeError:网络请求失败]

我的组件和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'
    }
});

的package.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 个答案:

答案 0 :(得分:4)

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

  1. 使用设备
  2. 使用模拟器
  3. 关键点在命令

    下面运行
      

    $ adb reverse tcp:3001 tcp:3001

         

    模板:adb reverse tcp:{APPLICATIONPORT} tcp:{APPLICATIONPORT}

    第一种情况是pc内的ipconfig,找到本地IP地址,如 192.168.1.4 。您的网址应该是http://192.168.1.4:3001/user/register

    如果您使用模拟器,则应使用以下网址http://10.0.2.2:3001/user/register

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

答案 1 :(得分:0)

Public Property ROOTS_BOTTOM As CodedValue
    Get
        Dim temp As CodedValue = MyBase.GetCodeDomainValue(Constants.COL_TILL_ROOTS_BOTTOM)
        If temp IsNot Nothing Then
            Return MyBase.AddRemoveErrorMsg(MyBase.GetCodeDomainValue(Constants.COL_TILL_ROOTS_BOTTOM), My.Resources.SystemMessages.TillRootsBottomRequired)
        Else
            Return MyBase.AddRemoveErrorMsg(MyBase.GetCodeDomainValue(Constants.COL_TILL_ROOTS_BOTTOM), My.Resources.SystemMessages.TillRootsBottomRequired)
        End If
        Return MyBase.AddRemoveErrorMsg(MyBase.GetCodeDomainValue(Constants.COL_TILL_ROOTS_BOTTOM), My.Resources.SystemMessages.TillRootsBottomRequired)
    End Get

    Set(value As CodedValue)
        If ROOTS_BOTTOM Is Nothing Then
            MyBase.SetAttributeValue(Constants.COL_TILL_ROOTS_BOTTOM, MyBase.AddRemoveErrorMsg(value, My.Resources.SystemMessages.TillRootsBottomRequired))
        End If
        If ROOTS_BOTTOM.Code.ToString = "Y" Then
            ROOT_DIST_MAX.Value = C_BOUNDARY_LOW.Value
            MyBase.SetAttributeValue(Constants.COL_TILL_ROOTS_BOTTOM, MyBase.AddRemoveErrorMsg(value, My.Resources.SystemMessages.TillRootsBottomRequired))
        Else
            MyBase.SetAttributeValue(Constants.COL_TILL_ROOTS_BOTTOM, MyBase.AddRemoveErrorMsg(value, My.Resources.SystemMessages.TillRootsBottomRequired))
        End If
    End Set
End Property

Public Property ROOT_DIST_MAX As Short?
    Get
        Return MyBase.GetShortValue(Constants.COL_TILL_ROOT_DIST_MAX)
    End Get
    Set(value As Short?)
        MyBase.SetAttributeValue(Constants.COL_TILL_ROOT_DIST_MAX, value)
    End Set
End Property

Public Property C_BOUNDARY_LOW As Short?
    Get
        Return MyBase.AddRemoveErrorMsg(MyBase.GetShortValue(Constants.COL_TILL_C_BOUNDARY_LOW), My.Resources.SystemMessages.TillCBoundaryLowRequired)
    End Get
    Set(value As Short?)
        MyBase.SetAttributeValue(Constants.COL_TILL_C_BOUNDARY_LOW, MyBase.AddRemoveErrorMsg(value, My.Resources.SystemMessages.TillCBoundaryLowRequired))
    End Set
End Property

第一个是您应该指向的那个