Search code examples
ruby-on-railsiphonereact-nativeexpometro-bundler

How do I connect to a local Rails back-end via a React Native app running on Expo?


I've inherited a fairly complex React Native app, so apologies in advance if I don't know everything I should know about the app as I ask this question.

I have a React Native app that uses Expo. I run expo start to start up Metro in the browser. I then use the LAN option to connect my iPhone to the local app via the Expo app on my phone. When I use LAN, I connect to the local app on my computer via an IP address that looks like 192.168.0.xxx:19000.

The app loads fine on my phone, but whenever I attempt a network request (i.e., a fetch call to the Rails server also running on my local machine), the app can't seem to connect to the back-end.

I am running the Rails server with the following command: rails server

Once the Rails server is running, I can go to 127.0.0.1:3000 in my browser to see the back-end of the app created in Rails.

However, whenever I make a fetch request from the app to the API at either 127.0.0.1:3000 or 192.168.0.xxx:19000 (the xxx is an actual three-digit number), the request fails. Basically, I cannot for the life of me figure out how to make a proper request from the React Native app running on my phone via Expo to the Rails server running on my local machine.

I have tried things like http vs. https, but no luck. I've also Googled the heck out of this, and I still can't figure out what's going on. Part of the problem is that the app itself is so large and complex and I'm still so new to it that I'm not sure if I'm just fundamentally misunderstanding how Expo and React Native are supposed to make requests to a back-end, or if the app itself has something quirky in it that's preventing me from making requests.

Any advice/ideas on how I can potentially get the app to properly connect to the Rails server would be greatly appreciated. Thank you.


Solution

  • You need to either run the react app locally as well in order to have it access the local backend, or change the port of the localhost application to make it accessible to the internet.

    As you stated, running something like

    $ rails server -b 0.0.0.0
    

    Will allow you to access it.