ansonws
ansonws

Reputation: 88

How can I configure app.json to accept all connection types such as HTTP requests?

In my Expo React Native app, I've been trying to fetch data from my Ruby on Rails API but it seems that http connections are not allowed.

All the solutions I've found either add configuration to AndroidManifest.xml in Android and Info.plist in iOS which I can't access, but I'd rather keep development in Expo instead of ejecting. I've tried changing localhost to 127.0.0.1, 10.0.2.2, and my machine's IP as well, but none worked. I've looked at the documentation for configuration with app.json and networking but I can't find anything about configuring App Transport Security within Expo. I'm currently running Expo on android 9.0 Pie.

fetch(`http://localhost:3000/api/v1/trainers`, {
    headers: { 
    Accept: 'application/json',
    "Content-Type": "application/json" 
},
}).then(res => res.json())
.catch(err => console.log(err));
TypeError: Network request failed
    at XMLHttpRequest.xhr.onerror (420454d9-7271-44d5-b…-3a968d130699:48065)
    at XMLHttpRequest.dispatchEvent (420454d9-7271-44d5-b…-3a968d130699:53513)
    at XMLHttpRequest.setReadyState (420454d9-7271-44d5-b…-3a968d130699:52368)
    at XMLHttpRequest.__didCompleteResponse (420454d9-7271-44d5-b…-3a968d130699:52195)
    at 420454d9-7271-44d5-b…-3a968d130699:52305
    at RCTDeviceEventEmitter.emit (420454d9-7271-44d5-b…-3a968d130699:22482)
    at MessageQueue.__callFunction (420454d9-7271-44d5-b…-3a968d130699:22097)
    at 420454d9-7271-44d5-b…-3a968d130699:21854
    at MessageQueue.__guard (420454d9-7271-44d5-b…-3a968d130699:22051)
    at MessageQueue.callFunctionReturnFlushedQueue (420454d9-7271-44d5-b…-3a968d130699:21853)

Upvotes: 3

Views: 1857

Answers (1)

dar
dar

Reputation: 97

What domain is your REST api on? I was having the same problem with fetching from a react native app (running on an emulator) to a node.js/express REST api. I couldn't find a workaround within React.

I found a solution with ngrok (https://ngrok.com). It allows you to expose a specific local domain:port to the outside. With this method I was able to fetch from my app to my REST api.

To be clear, I'm not sure the problem is on React-Native's end. I suspect it was my firewall not allowing the connection to go through. Instead of messing with all of those settings, I simply used ngrok.

Upvotes: 4

Related Questions