How to solve 'TypeError: Network request failed' in React Native?

Viewed 15749

Environment

I'm developing a mobile app with React Native and Expo.

Also, developing api with Laravel that is in my local environment. (http://localhost:8000/)

This app is working on Expo client app.

What I'm trying to do

I wanna get datas from api.

Code

App.js

componentDidMount() {
  return fetch('http://localhost:8000/api/test')
    .then((response) => response.json())
    .then((responseJson) => {
      console.log(responseJson);
    })
    .catch((error) => {
      console.error(error);
    });
}

Error

TypeError: Network request failed

Expo version

3.22.3

I would appreciate it if you could give me any advice.

3 Answers

you should not use http://localhost:8000 for your base URL, please use your IP Address.

if you use Macbook, you can find the IP in System Preferences > Network

find ip

then use fetch('http://172.20.10.5:8000/api/test') in your react native app.

if my base URL when access via browser is http://172.20.10.5:8000/mysite/api/test you need fetch in react native fetch('http://172.20.10.5:8000/mysite/api/test')

basically, android & ios did not allow request using HTTP, you need to do something below to allow HTTP connection instead of HTTPS.

android

and then add android:usesCleartextTraffic="true" in your Android manifest android/app/src/main/AndroidManifest.xml

iphone

add this in info.plist

<key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key>
        <true/>
        <key>NSExceptionDomains</key>
        <dict>
            <key>localhost</key>
            <dict>
                <key>NSExceptionAllowsInsecureHTTPLoads</key>
                <true/>
            </dict>
        </dict>
    </dict>

if after this it not work, disable you firewall

Related