Home > Blockchain >  Fetch requests with React Native
Fetch requests with React Native

Time:06-30

whenever I do fetch requests with react native to an API, it gives me this error code:

[TypeError: Network request failed]

Does anyone know what this means?

I checked Stackoverflow and it was said that I need to update my info.plist, however that didn't fix the issue unfortunately

I added this to my info.plist

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>weatherapi.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

This is the code I use to fetch, the URL works. My ReactJS app successfully sends the requests

const [degreesCelsius, setDegreesCelsius] = useState(0);

  const fetchInformation = useCallback(async () => {
    try {
      const result = await fetch(
        "http://api.weatherapi.com/v1/current.json?key=140ce0a625221404&q=Berlin&aqi=yes",
      );

      if (result.ok) {
        const data = await result.json();
        setDegreesCelsius(data.current.temp_c);
        console.log(degreesCelsius);
      }
    } catch (e) {
      console.error(e);
    }
  }, []);

CodePudding user response:

Assuming this isn't an issue with the fetch request the domain specified in your .plist appears to also be incorrect. For now I would just recommend setting NSAllowArtbitraryLoads key to true which will allow your app to make any request as long as it's using https

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSExceptionDomains</key>
    <dict>
        <key>localhost</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
        </dict>
        <key>myweather.com</key>
        <dict>
            <key>NSExceptionAllowsInsecureHTTPLoads</key>
            <true/>
            <key>NSIncludesSubdomains</key>
            <true/>
        </dict>
    </dict>
</dict>

During development I find this approach much easier, if security is paramount to the application then you can come back and update the allowed domains later.

const result = await fetch(
  'https://api.myweather.com/' // this also needs to be a url,
);

Also the url in your fetch request needs to be valid, since it appears you are using a subdomain as well you will need to add the NSIncludesSubdomains key as well.

https://developer.apple.com/documentation/bundleresources/information_property_list/nsexceptionallowsinsecurehttploads?language=objc

Also make sure to recompile after updating the .plist either from within xcode or by running npx react-native run-ios :)

  • Related