Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
  }
}
like image 322
Yunus Avatar asked Mar 10 '18 07:03

Yunus


People also ask

How do I connect React Native to local server?

Running your React Native applicationInstall the Expo Go app on your iOS or Android phone and connect to the same wireless network as your computer. On Android, use the Expo Go app to scan the QR code from your terminal to open your project. On iOS, use the built-in QR code scanner of the default iOS Camera app.

How do I get localhost API in React Native?

In Android, we can use the IP 10.0. 2.2 to access computers localhost. In a project, we can use the above logic to decide what baseUrl to use based on the platform. Afterwards, we can use this baseUrl for all APIs.

How fetch data from localhost in react?

Step to run the application: Open the terminal and type the following command. Output: Now open localhost:300 and in the console, the data is fetched. 2. Axios Package: Axios is a promise-based HTTP client designed for Node.


1 Answers

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.

like image 65
Yunus Avatar answered Nov 01 '22 04:11

Yunus