React Native Android Fetch failing on connection to local API

前端 未结 9 1852
被撕碎了的回忆
被撕碎了的回忆 2020-11-28 22:08

I\'m using the fetch API in my react-native Android app to make requests to a local API. I usually query said API from react web apps at http://localhost:8163.

I\'m t

9条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-28 22:52

    Had the same/similar issue - took me two full days to solve it. I use a Win10 machine with Visual Studio Code, attached Android device and a local PHP server for API. Maybe this will help somebody:

    1. Cable -> Try different USB-cables, out of my 3 cables only one works
    2. Connection mode -> Very important, I had to choose PTP mode to make it work
    3. Same network -> Phone and PC must be on the same network
    4. Private network -> The network must be a private network, public does not work
    5. IP -> Run ipconfig in PowerShell and get your IP4 address
    6. Firewall -> Accept the firewall-prompt
    7. PHP server -> Start built in PHP server with "php -S {your IP}:8081"
    8. Test PHP server -> Create index.php and open {your IP}:8081 on your phone
    9. Fetch -> Create fetch script (example below)

           fetch('http://{your IP}:8081/')
          .then((response) => response.json())
          .then((responseJson) => {
            this.setState({ message : responseJson.message.data })
            })
          .catch((error) => {
            console.error(error);
          }); 

提交回复
热议问题