Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch doesn't work in React Native ios

I have login function in React Native where I try to fetch data. The function is as follows:

onLogin: function() {  //
        const self = this;
        self.setState({modalVisible: true, modalMessage: 'Signing in'});
        fetch('http://psa.autralis.com/manager/api/v1/obtain-auth-token/', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                username: self.state.username,
                password: self.state.password,
            })
        })
            .then(response => response.json())
            .then(data => console.log(data))
            .catch((error) => {
                console.warn(error);
            });
    },

But for some reason it doesn't work on ios. I get an error :

enter image description here

On android it works, and I tested it with postman and there also works.

Any idea?

like image 577
Boky Avatar asked Jun 30 '26 21:06

Boky


2 Answers

The reason for this problem is that: iOS does not allow http requests by default, only https. If you need to do this with http, just change your info.plist:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>
like image 193
calvin1992 Avatar answered Jul 02 '26 13:07

calvin1992


In case someone else needs it. I solved it by adding

<key>NSAllowsArbitraryLoads</key>
<true/>

to a Info.plist file which is located inside ios folder in your project.

Thus I changed

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

with

<key>NSAppTransportSecurity</key>
    <dict>
      <key>NSAllowsArbitraryLoads</key>
      <true/>
      <key>NSExceptionDomains</key>
      <dict>
        <key>localhost</key>
        <dict>
          <key>NSExceptionAllowsInsecureHTTPLoads</key>
          <true/>
        </dict>
      </dict>
    </dict>
like image 24
Boky Avatar answered Jul 02 '26 12:07

Boky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!