0

Flipper Screenshot I am creating an app where I click on the login button to open the home page but after clicking the log-in button I am getting a network error. This error persists only when I run through the app, while I tried the API through postman everything works fine. And I also tried replacing localhost with my IP address and also inserting android:usesCleartextTraffic="true" in the android manifest but nothing seems to work

Server.js

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const dbConfig = require("./app/config/db.config");

const app = express();

// var corsOptions = {
//   origin: "http://localhost:8081"
// };

app.use(cors());

// parse requests of content-type - application/json
app.use(bodyParser.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: true }));

const db = require("./app/models");
const Role = db.role;

db.mongoose
  .connect(`mongodb+srv://admin:<Mypassword>@cluster0.wmdoe.gcp.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log("Successfully connect to MongoDB.");
    initial();
  })
  .catch(err => {
    console.error("Connection error", err);
    process.exit();
  });

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to bezkoder application." });
});

// routes
require("./app/routes/auth.routes")(app);
require("./app/routes/user.routes")(app);

// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

function initial() {
  Role.estimatedDocumentCount((err, count) => {
    if (!err && count === 0) {
      new Role({
        name: "user"
      }).save(err => {
        if (err) {
          console.log("error", err);
        }

        console.log("added 'user' to roles collection");
      });

      new Role({
        name: "moderator"
      }).save(err => {
        if (err) {
          console.log("error", err);
        }

        console.log("added 'moderator' to roles collection");
      });

      new Role({
        name: "admin"
      }).save(err => {
        if (err) {
          console.log("error", err);
        }

        console.log("added 'admin' to roles collection");
      });
    }
  });
}

LoginScreen.js

/* eslint-disable no-shadow */
/* eslint-disable react-native/no-inline-styles */
/* eslint-disable prettier/prettier */
import React, {useState, useEffect} from 'react';
import {TextInput, SafeAreaView,ScrollView,TouchableWithoutFeedback,Text, View, StyleSheet, Image} from 'react-native';
import Header from '../components/Header';
import {localizdStrings}  from '../LocalizedConstants';
import { useNavigation } from '@react-navigation/native';
import CheckBox from '@react-native-community/checkbox';
import LinearGradient from 'react-native-linear-gradient';
import { SocialIcon } from 'react-native-elements';
import AsyncStorage from '@react-native-community/async-storage';
import GradientHeader from 'react-native-gradient-header';
import LocalizedStrings from 'react-native-localization';
import { showMessage } from 'react-native-flash-message';
import API from '../Config/API';
import axios from 'axios';

const LoginScreen = ({props}) => {
  const navigation = useNavigation();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [toggleCheckBox, setToggleCheckBox] = useState(false);
  const showErrorMessage = (message,type) => {
    return showMessage({
      message: message,
      type: type,
      color: '#ffffff',
      fontSize: 14,
      fontWeight: 'bold',
      backgroundColor: '#0C254B',
  });
};

const ValidateEmail = (inputText) => {
    var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
    if (inputText.match(mailformat)) {
        return true;
    }
    else {
        return false;
    }
};
const validate = async () =>{
  if (email === '' || email === undefined || email === null) {
   return showErrorMessage("Email can't be blank",'danger');

}
else if (ValidateEmail(email) === false) {
   return showErrorMessage('Enter a valid Email address','danger');
}

else if (password === '' || password === undefined || password === null) {
   return showErrorMessage("Password can't be blank",'danger');
}
 else {
    // const data = JSON.stringify({
    //   'email': email,
    //   'password': password,
    // });
    const options = {
      method: 'post',
      headers:{'Content-type': 'application/json'},
      url: 'http://localhost:8080/api/auth/signin',
      data: {
        email: email,
        password: password,
      },
      transformResponse: [(data) => {
        return data;
      }]
    };
  const res = await axios(options).then((res)=>{
    if (res.data.success === true){
      //navigation.navigate('Auth');
      navigation.navigate('Home');

     // navigation.navigate('Service',{screen:'Doppler'});
     //showErrorMessage(response.data.message,'success')
     }
     console.log(res.status);
   }).catch((error)=> {
    console.log(error);
    });
 }
};
  return (
    <SafeAreaView style={styles.outerContainer}>
      <View style={{flex:1}}>
        <Header />
        <ScrollView style={styles.scrollView}>
        <TextInput
          placeholder= {localizdStrings.EmailOrMobile}
          style={styles.TextInput}
          onChangeText={(email) => setEmail(email)}
          value={email}
          keyboardType = {'email-address'}
          autoCapitalize = "none"
          autoCorrect = {false}
        />
        <TextInput
          placeholder= {localizdStrings.Password}
          style={styles.TextInput}
          onChangeText={(password) => setPassword(password)}
          value={password}
          autoCapitalize = "none"
          returnKeyType={'done'}
          secureTextEntry={true}
          autoCorrect = {false}
        />
        <View style={{flexDirection:'row',  marginLeft:20, width:380, padding:10}}>

        <View style={{flexDirection:'row', justifyContent:'flex-start',alignItems:'center'}}>
          <View style={styles.rememberMe}>
         <CheckBox
          disabled={false}
          value={toggleCheckBox}
          tintColors={{true: '#ff0000'}}
          onValueChange={(newValue) => setToggleCheckBox(newValue)}
        />
        <Text>{localizdStrings.RememberMe}</Text>
        </View>
        </View>
        <View style={{flexDirection:'row', justifyContent:'flex-end',alignItems:'center', marginLeft:50 }}>

        <View style={styles.forgetPass}>
        <Text style={{color:'grey'}}>{localizdStrings.ForgetThePassword}</Text>
        </View>
        </View>
        </View>
        <TouchableWithoutFeedback onPress={() => validate()}>
        <LinearGradient start={{x: 1, y: 0}} end={{x: 0, y: 0}} colors={['#29B6F6', '#29B6F6', '#0231C1']} style={styles.gradientStyle}>
                <View style={styles.Loginbutton}>
                    <Text style={{fontWeight:'bold', fontSize:20, color:'white'}}>{localizdStrings.Login}</Text>
                </View>
        </LinearGradient>
        </TouchableWithoutFeedback>
        <View style={styles.quickAcess}>
        <Text style={{fontWeight:'bold', marginTop:5}}> {localizdStrings.OrQuickAccessWith} </Text>
        <View style={{ margin:5}}>
          <TouchableWithoutFeedback >
          <View style={styles.button}>
            <Image source={require('../images/facebook.png')}
          style={styles.socialIcon}
        />
        <Text style={styles.socialLoginText}>{localizdStrings.Facebook}</Text>
        </View>
        </TouchableWithoutFeedback>

        <TouchableWithoutFeedback>
          <View style={styles.button}>
            <Image source={require('../images/google.png')}
          style={styles.socialIcon}
        />
        <Text style={styles.socialLoginText}>{localizdStrings.Google}</Text>
        </View>
        </TouchableWithoutFeedback>
        <TouchableWithoutFeedback onPress={()=> navigation.navigate('RegisterScreen')}>
        <Text style={{marginLeft:95,marginRight:120, fontWeight:'bold', fontSize:18}}>{localizdStrings.CreateANewAccount}</Text>
        </TouchableWithoutFeedback>
        <View style={{marginLeft:150,marginRight:150}}>
        <Image source={require('../images/color_logo.png')} style={{resizeMode:'contain',height:80, width:100}} />
        <Image source={require('../images/labelwhite.png')} style={{resizeMode:'contain', height:80, width:100}} />
        </View>
        </View>
        </View>
        </ScrollView>
      </View>
    </SafeAreaView>
  );
};

export default LoginScreen;

const styles = StyleSheet.create({
    outerContainer:{
      flex:1,
    },
    Loginbutton: {
      alignItems: 'center',
      paddingLeft: 60,
      paddingRight:60,
      paddingBottom:10,
      paddingTop:10,
      borderRadius:20,
      marginBottom:10,
      marginLeft: 40,
      marginRight: 40,
      height:50,
    },
    socialLoginText:{
      color:'#00838F',
      //marginLeft:-50,
      paddingLeft:40,
    },
    socialIcon:{
      marginRight:50,
      marginLeft:-50,
    },
    scrollView: {
      backgroundColor: 'white',
      marginTop:100,
    },
    text: {
      fontSize: 42,
    },
    TextInput: {
      height: 50,
      flex: 1,
      paddingLeft: 20,
      paddingRight: 20,
      marginLeft: 40,
      marginRight: 40,
      borderColor: '#0277BD',
      borderRadius: 30,
      borderWidth: 1,
      marginBottom:5,
      marginTop:40,
    },
    rememberMe:{
      flexDirection:'row',
      alignItems:'center',
      padding:10,
      marginLeft: 5,
    },
    forgetPass:{
      flexDirection:'row',
      alignItems:'center',
      padding:10,
    },
    gradientStyle:{
      alignItems: 'center',
      borderRadius:20,
      marginBottom:10,
      marginLeft: 40,
      marginRight: 40,
      height:50,
    },
    quickAcess:{
      alignItems:'center',
    },
    button: {
      alignItems: 'center',
      backgroundColor: 'white',
      paddingLeft: 60,
      paddingRight:60,
      paddingBottom:10,
      paddingTop:10,
      borderWidth:1,
      borderColor:'#0277BD',
      borderRadius:8,
      flexDirection:'row',
      margin:15,
    },
});

Error in console

[Error: Network Error]

  • if you debug the application in the chrome inspector, do you see what the response is to the call? Can you share that? You'll have to enable requests to be logged into the inspector, I use this approach - https://stackoverflow.com/a/42952086/518341 – Chris Mar 10 '21 at 10:38
  • Alternatively, you can use Flipper to see them also. – Chris Mar 10 '21 at 10:38
  • I have included the screenshot of flipper – prateek chauhan Mar 10 '21 at 10:57
  • Instead of localhost use IP address of your server. change this to http://localhost:8080/api/auth/signin to something like http://192.168.x.x:8080/api/auth/signin – Imran Shad Mar 10 '21 at 11:41

1 Answers1

0

localhost doesn't works well on React Native apps. So instead of localhost use IP address of your server. change this to http://localhost:8080/api/auth/signin to something like 192.168.x.x:8080/api/auth/signin

Imran Shad
  • 58
  • 13