Yunus
Yunus

Reputation: 731

React native android connect backend service at localhost

I have a register service which is handled by Nodejs. This service is working on 3001 port. I try to connect this service from React Native application. But always returns

ReactNativeJS: [TypeError: Network request failed]

My component and package.json code is below. Also, I replaced URL localhost to 127.0.0.1 and it does not work. Backend service is working properly when I test it from Postman. Gives very common exception Network Error, so it is very hard to understand the root of the problem. Every React Native development starter can easily face with this problem. So problem caused from React Native or 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="[email protected]"
                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"
  }
}

Upvotes: 11

Views: 12961

Answers (2)

rabiaasif
rabiaasif

Reputation: 312

ifconfig | grep "192.168"

the first one is the one you should be pointing at

Upvotes: 0

Yunus
Yunus

Reputation: 731

There could be 2 cases to test this problem.

  1. Use Device
  2. Use Emulator

Key point is run below command

$adb reverse tcp:3001 tcp:3001

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

The first case is ipconfig inside pc and find local IP address like 192.168.1.4. Your url should like http://192.168.1.4:3001/user/register

If you use emulator, you should use following url like http://10.0.2.2:3001/user/register

These URLs worked me, after running adb reverse command.

Upvotes: 15

Related Questions