1

I'm trying to fetch a locally hosted API from ASP.NET server:

 try {
 const response = await fetch(`https://localhost:2318/api/Restaurant`)
 const data = await response.json()
 console.log(data)
 } catch (error) {
 console.error(error)
 }

However, it throws an error:

Network request failed
at node_modules/whatwg-fetch/dist/fetch.umd.js:535:17 in setTimeout$argument_0

None of my endpoints work. Fetching from public APIs works. Also strange that opening the fetching url https://localhost:2318/api/Restaurant in Safari inside the simulator works and returns the data as expected.

I'm using Expo v42.0.1, RN v0.66.

Any ideas?

asked Oct 19, 2021 at 15:56
2
  • Are you sure it is https? Commented Oct 19, 2021 at 17:13
  • @KenyiLarcher I'm pretty sure yes, because entering url with https works in simulator's safari, while entering url with http says "Safari cannot open the page because the network connection was lost." Commented Oct 19, 2021 at 17:21

1 Answer 1

1

You are making a request to the localhost server which is going to have a self-signed certificate. So either iOS or Android won't allow fetching from that API straightaway.

The easiest solution would be using react-native-fetch-blob. (Just pass trusty as true).

RNFetchBlob.config({
 trusty : true
})
.then('GET', 'https://example.com')
.then((resp) => {
 // ...
})

And if you still want to use fetch and try the below solution.

  1. If you are using the iOS device to test : You can do two things:
  • Either you can make an HTTP call (change https to http in your url) using the below implementation.

If you want to enable HTTP requests add this to your info.plist:

<key>NSAppTransportSecurity</key>
<dict>
 <key>NSAllowsArbitraryLoads</key>
 <true/>
</dict>
  1. If you are using an Android device to test :

    Try the below solution : https://stackoverflow.com/a/55246927/8893384

marc_s
761k186 gold badges1.4k silver badges1.5k bronze badges
answered Oct 19, 2021 at 17:31
Sign up to request clarification or add additional context in comments.

react-native-fetch-blob doesn't work with Expo as I understand. I ended up changing our local server's URL to HTTP only, fetching from which works perfectly fine in React Native. I think in the future we'll have to think about signing a normal certificate.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.