React Native 在Expo Go应用程序中发出API请求时发生网络错误

t3psigkw  于 2023-08-07  发布在  React
关注(0)|答案(1)|浏览(250)

我在Expo Go应用程序中遇到了一个问题,当我尝试使用loginUser和handleLogin函数发出API请求时,遇到了“Network request failed”错误。值得注意的是,同样的功能在Expo Web中完美地工作,成功地连接到API并获取数据。
我提供了下面两个函数的代码片段:

登录用户函数:

export const loginUser = async (username, password) => {
  try {
    const response = await fetch(`${BASE_URL}/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
    });

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Giriş yapılamadı:', error);
    throw new Error('Giriş yapılamadı: ' + error.message);
  }
};

字符串

--------------------------------------------------------------------
handleLogin函数:

const handleLogin = async () => {
  try {
    const response = await loginUser(username, password);

    if (response.message === 'Giriş başarılı.') {
      console.log('Login Successful');
      navigation.navigate('Second', {
        blogpost: username,
      });
    } else {
      console.log('User not found or incorrect password.');
      setErrorx('User not found or incorrect password.');
      setTimeout(() => {
        setErrorx('');
      }, 3000);
    }
  } catch (error) {
    console.error('Login error:', error);

    // Check if the error response has a data field with a message property
    const errorMessage = error.response?.data?.message || error.message || 'Login failed.';
    setErrorx(errorMessage);

    setTimeout(() => {
      setErrorx('');
    }, 3000);
  }
};

主页.js

import React, { useState, useEffect } from 'react';
import { View, Text, SafeAreaView, TextInput, TouchableOpacity, Linking, StyleSheet, Image} from 'react-native';
import { useNavigation } from '@react-navigation/native';
import { loginUser } from './fetchData';
import axios from 'axios';
import { Asset } from 'expo-asset';
import * as Font from 'expo-font';


export default function HomePage() {
  const [fontsLoaded, setFontsLoaded] = useState(false);
  const navigation = useNavigation();
  const logo = Asset.fromModule(require('../assets/LOGODEX.png')).uri;
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [errorx, setErrorx] = useState('');

  const handleUsernameChange = (text) => {
    setUsername(text);
  };

  const handlePasswordChange = (text) => {
    setPassword(text);
  };
  const handleSupportPress = () => {
    const message = "Merhaba, Uygulamanızla ilgili bir sorun yaşıyorum. Sorunum ise ...";
    const encodedMessage = encodeURIComponent(message);
    const url = `https://wa.me/SANSURED?text=${encodedMessage}`;
  
    Linking.openURL(url);
  };
  const handleRegisterPress = () => {
    const url =
      'https://wa.me/SANSURED?text=Merhaba%2C%20Uygulaman%C4%B1zda%20bir%20kay%C4%B1t%20olu%C5%9Fturmak%20istiyorum';
    Linking.openURL(url);
  };

  const handleLogin = async () => {
    try {
      const response = await loginUser(username, password);
  
      if (response.message === 'Giriş başarılı.') {
        console.log('Giriş Başarılı');
        navigation.navigate('Second', {
          blogpost: username,
        });
      } else {
        console.log('Kullanıcı bulunamadı veya şifre yanlış.');
        setErrorx('Kullanıcı bulunamadı veya şifre yanlış.');
        setTimeout(() => {
          setErrorx('');
        }, 3000);
      }
    } catch (error) {
      console.error('Login error:', error);
  
      // Check if the error response has a data field with a message property
      const errorMessage = error.response?.data?.message || error.message || 'Login failed.';
      setErrorx(errorMessage);
  
      setTimeout(() => {
        setErrorx('');
      }, 3000);
    }
  };
  
  



  useEffect(() => {
    const loadFonts = async () => {
      await Font.loadAsync({
        'my-custom-font': require('../assets/Seanor.ttf'),
      });
    
      setFontsLoaded(true);
    };
    

    loadFonts();
  }, []);

  // Font yüklenmediyse bekleme ekranı göster
  if (!fontsLoaded) {
    return (
      <View style={{ flex: 1, justifyContent: 'center', alignItems: 'center' }}>
        <Text style={{fontSize: 30}}>Fontlar yükleniyor...</Text>
      </View>
    );
  }








  return (
    <SafeAreaView style={styles.container}>



    

      

        <View style={{ zIndex: 2, position: 'absolute', top: 116, left: 22}}>

        <Image style={{zIndex: 3, width: 160, height: 88, position: 'absolute', top: -76, left:77}} source={{ uri: logo }} />

        <Text style={{ fontFamily: 'my-custom-font', fontSize: 21, textAlign: "center", color: 'white', fontWeight: '500', top: 23}}>
          TEST 
        </Text>
        </View>

        

      <View style={{ position: 'absolute',backgroundColor: '#607FF2', borderRadius: 350, height: 700, width: 700, zIndex: 1, top: -420, left: -230}}></View>
      <View style={{ position: 'absolute',backgroundColor: '#4C51C6', borderRadius: 350, height: 700, width: 700, zIndex: 1, top: -430, left: -250}}></View>
        
      <View style={styles.loginview}>
            <View style={{marginTop: 9,}}>
        <View style={styles.loginPadUsername}>

          <TextInput
            placeholder="Kullanıcı Adı"
            style={styles.padUsername}
            onChangeText={handleUsernameChange}
          />
        </View>

        <View style={styles.loginPadPassword}>
          <TextInput
            placeholder="Şifre"
            style={styles.padPassword}
            secureTextEntry={true}
            onChangeText={handlePasswordChange}
          />
        </View>



        <View style={{flexDirection: "row", marginTop: 17, zIndex: 3,}}>

          <TouchableOpacity style={styles.loginAddButton} onPress={handleRegisterPress}>
            <Text style={styles.buttonText}>Kayıt Ol</Text>
          </TouchableOpacity>

          <TouchableOpacity style={styles.loginPadButton} onPress={handleLogin}>
            <Text style={styles.buttonText}>Giriş Yap</Text>
          </TouchableOpacity>

        </View>
        <View style={{ height: 30, marginBottom: 4, justifyContent: "center", alignItems: "center", zIndex: 5, position: 'absolute', top: 268, left: 24 }}>
          <Text style={{ fontSize: 10, color: '#E9F4FF', zIndex: 5 }}>
            {errorx}
          </Text>
        </View>

            </View>
        </View>


        <TouchableOpacity style={{position: 'absolute', top: 580, left: 202, height: 80, width: 130, backgroundColor: 'white', zIndex: 3, justifyContent: 'center',borderRadius: 45,}}>
          <Text style={{fontSize: 22,textAlign: 'center'}}> Destek </Text>
        </TouchableOpacity>



        <View style={{ zIndex: 2, position: 'absolute', top: 680}}>
          <Text style={{fontFamily: 'my-custom-font', fontSize: 21, textAlign: "center", color: 'white', left: 24}}>
          TEST
          </Text>
        </View>
        

        <View style={{ position: 'absolute', backgroundColor: '#4C51C6', borderRadius: 350, height: 600, width: 600, zIndex: 1, top: 520, left: -15}}></View>
        <View style={{ position: 'absolute', backgroundColor: '#607FF2', borderRadius: 350, height: 600, width: 600, zIndex: 1, top: 550, left: -30}}></View>
      
      


   
   
   
   
    </SafeAreaView>
  );
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#blue',
    alignItems: 'stretch',
  },
  textcenter: {
    fontSize: 70,
    marginVertical: 80,
    textAlign: "center",
    zIndex: 3
  },
  loginview: {
    flex: 1,
    backgroundColor: "#FD830D",
    alignItems: "center", 
    justifyContent: 'center',
    zIndex: 0,
    position: 'absolute',
    top: 4,
    left: -66,
    height: 700,
    width: 500,
  },
  loginPadUsername: {
    backgroundColor: "#E9F4FF",
    borderRadius: 23,
    marginTop: 80,
    zIndex: 3
  },
  padUsername: {
    padding: 11,
    fontSize: 22,
    width: 210,
    textAlign: "center",
    zIndex: 3
  },
  loginPadPassword: {
    backgroundColor: "#E9F4FF",
    borderRadius: 23,
    marginTop: 17,
    zIndex: 3
  },
  padPassword: {
    textAlign: "center",
    padding: 11,
    fontSize: 22,
    width: 211,
    zIndex: 3
  },

  PadButton: { 
    textAlign: "center",
    fontSize: 17,
    padding: 9,
  },
  loginPadButton: { 
    backgroundColor: "#8BC34A",
    borderRadius: 22,
    alignItems: "center",
    justifyContent: "center",
    marginStart: 30,
    padding: 15,
  },
  loginAddButton: {
    backgroundColor: "#8BC34A",
    borderRadius: 22,
    alignItems: "center",
    justifyContent: "center",
    padding: 15,
  },
  AddButton: {
    padding: 9,
    fontSize: 17,
    textAlign: "center",
  },

  buttonText: {
    fontSize: 20,
    textAlign: "center",   
}
});

fetchData.js

import axios from 'axios';
import axiosInstance from './axiosInstance';

const BASE_URL = 'API URL SANSURED'; // MySQL API URL'sini buraya ekleyin





export const updateUser = async (userId, updatedData) => {
  try {
    const newData = {
      ...updatedData, // Eski verileri kopyala
      izinyellow: updatedData.izinyellow, // 'izinyellow' anahtarını ekle
    };

    await axios.put(`${BASE_URL}/veridegistir`, newData);
    console.log('Veri başarıyla güncellendi');
  } catch (error) {
    throw new Error('Veri güncellenirken hata oluştu: ' + error.message);
  }
};



export const loginUser = async (username, password) => {
  try {
    const response = await fetch(`${BASE_URL}/login`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ username, password }),
    });

    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Giriş yapılamadı:', error);
    throw new Error('Giriş yapılamadı: ' + error.message);
  }
};



export const updateYellowPhoneAndPass = async (useridpost, yellowPhone, yellowPass, xerror) => {
  try {
    const response = await axios.get(`${BASE_URL}/verioku`);
    const users = response.data;
    const user = users.find((u) => u.username === useridpost);
    if (user) {
      await axios.put(`${BASE_URL}/yellowphoneandpassword`, {
        id: user.id,
        emailyellow: yellowPhone,
        passyellow: yellowPass,
        checkyellow: 1,
      });
      console.log('Yellow telefon ve şifre bilgileri başarıyla güncellendi');
    }
  } catch (error) {
    throw new Error('Yellow telefon ve şifre bilgileri güncellenirken hata oluştu: ' + error.message);
  }
};



export const updateWhiteEmailAndPass = async (useridpost, whitePhone, whitePass, xerror) => {
  try {
    const response = await axios.get(`${BASE_URL}/verioku`);
    const users = response.data;
    const user = users.find((u) => u.username === useridpost);
    if (user) {
      await axios.put(`${BASE_URL}/whiteemailandpassword`, {
        id: user.id,
        emailwhite: whitePhone,
        passwhite: whitePass,
        checkwhite: 1,
      });
      console.log('Yellow telefon ve şifre bilgileri başarıyla güncellendi');
    }
  } catch (error) {
    throw new Error('Yellow telefon ve şifre bilgileri güncellenirken hata oluştu: ' + error.message);
  }
};





export const updateYellowTimeCode = async (useridpost, yellowTimeCode, yellowWork, yellowMesaj) => {
  try {
    const response = await axios.get(`${BASE_URL}/verioku`);
    const users = response.data;
    const user = users.find((u) => u.username === useridpost);
    if (user) {
      await axios.put(`${BASE_URL}/yellowtimecode`, {
        id: user.id,
        timecodeyellow: yellowTimeCode,
        workyellow: yellowWork,
        mesajyellow: yellowMesaj,
      });
      console.log('Time Ayarlandı');
    }
  } catch (error) {
    throw new Error('Time HATA : ' + error.message);
  }
};









export const updateWhiteTimeCode = async (useridpost, whiteTimeCode, whiteWork, whiteMesaj) => {
  try {
    const response = await axios.get(`${BASE_URL}/verioku`);
    const users = response.data;
    const user = users.find((u) => u.username === useridpost);
    if (user) {
      await axios.put(`${BASE_URL}/whitetimecode`, {
        id: user.id,
        timecodewhite: whiteTimeCode,
        workwhite: whiteWork,
        mesajwhite: whiteMesaj,
      });
      console.log('Time Ayarlandı');
    }
  } catch (error) {
    throw new Error('Time HATA : ' + error.message);
  }
};





export const getYellowError = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/yellowerror`);
    return response.data;
  } catch (error) {
    throw new Error('Yellow hatalarını alırken bir hata oluştu: ' + error.message);
  }
};


这个问题特别发生在Expo Go上的两个Android设备上,我已经测试了该应用程序。我已验证两台设备均具有活动的互联网连接。API在Expo Web上按预期工作,所以我很困惑为什么我在Expo Go中遇到网络错误。
我已经检查了真实的设备上的权限,并向应用程序授予了必要的互联网权限。此外,SSL证书配置似乎是为了作为API的功能,没有任何问题的博览会网站。
我正在寻求指导,以了解此问题的根本原因,并找到解决方案,以确保我的Expo Go应用程序可以成功发出API请求。
任何帮助或见解解决这个网络错误在世博会去将不胜感激。提前感谢您的帮助!是的,我的英语不好,我用翻译,而写作

ifsvaxew

ifsvaxew1#

检查你的API url,使用ip address代替http://localhost:3000使用http:191.168....:5000代替。检查你正在运行后端的机器的确切地址。我也是这么解决的。

相关问题