React Native Fetch on Android returns Network request failed

可紊 提交于 2021-02-04 08:28:26

问题


I am building a React Native mobile application that is using a Laravel backend, currently running on localhost:8000. When making a fetch request from an Android device to my server, my application gets the following error logs:

My code is below:

export default class App extends Component {
 login() {
    fetch('http://localhost:8000/api/establishments/get')
      .then((response) => response.json())
      .then((responseJson) => {
        console.log('success!');
      })
      .catch((error) => {
        console.error(error);
      });
  }

  render() {
    return (
      <TouchableOpacity activeOpacity={.5} onPress={() => this.login()}>
        <Text>Sign In</Text>
      </TouchableOpacity>
    );
  }
}

When I copy and paste the exact route into my browser, the server responds successfully and completely as expected. I believe it is an issue with network permissions from my application? I have only just began learning React Native a week ago and would appreciate any help at all.


回答1:


I suspect that 127.0.0.1 or localhost will point to the emulator itself in your computer where the server is currently running. Try replacing 127.0.0.1 / localhost with 10.0.2.2 if you are on AVD or 10.0.3.2 if you are on Genymotion or with your computer's actual IP address. In addition, you should also make sure that your android app can use internet. You can do that by adding

<uses-permission android:name="android.permission.INTERNET" />

in your AndroidManifest.xml.




回答2:


iOS runs in a simulator while Android runs in an emulator. Emulator emulates a real device, while simulator only imitates a device. Therefore localhost on Android points to the emulated Android device instead of the machine where your server runs. You should change localhost in yours request paths with the IP address of your machine.

More details at: https://github.com/facebook/react-native/issues/10404#issuecomment-267303151




回答3:


Founded solution for Laravel and react native (Physical device)

  1. open cmd run ipconfig copy ipv4 address for example my ipv4 address is 192.168.43.235
  2. Connect same network for laptop and physical device or open hotspot and connect same network
  3. Now run command start laravel backend php artisan serve --host=192.168.43.235 --port=8000
  4. change api url from react native api service

apiServise.js

    import axios from 'axios';
    
    const api_url = 'http://192.168.43.235:8000';
    
    export const getCategories = request =>
  axios
    .get(api_url + '/api/categories', {
      params: request || {},
    })
    .then(response => response.data);

homescreen.js

import {getCategories} from '../services/ApiService';

async fetchCategories() {
    await getCategories()
      .then(response => {
        this.setState({
          dataCategories: response
        });
      })
      .catch(error => {
        console.log(error);
      });
  }
  1. Now run command start react native app react-native run-android

that is all...now api request working fine.




回答4:


Change http://localhost:8000/api/establishments/get localhost with, which can your emulator reach generally 10.0.2.2 ;) have phun.



来源:https://stackoverflow.com/questions/45292489/react-native-fetch-on-android-returns-network-request-failed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!