top of page
Search
  • Writer's picturePatrick Hoehn

How to set up React Native to talk to your localhost Ruby on Rails backend.

So you are creating a React Native app and you have built a backend API for it to pull information from. You are doing a fetch call that may look like

fetch(`"http://localhost:3000"`, {
  method: "POST",
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
   },
 body: JSON.stringify(value)
})

You're excited and try to load up your code on your phone or emulator but you get a React Native error that looks like

Warning: Possible Unhandled Promise Rejection(id: 1):
TypeError: Network request failed

The reason this is happening is because the code is actually being run from the phone or emulator directly. This means when you type in "localhost" it is not looking at your computer anymore. It is looking at the local host of the phone or emulator which isn't running anything. Hence you get the network request failed error. There is nothing running where you are pointing to it. The easiest way to fix this would be to host your backend on a site like Heroku but if you wanted to leave it as a local backend for now, you can. This tutorial will walk you through the steps.


STEP ONE


Create a new file named BackendURL.js. You need to find your local I.P. address. On mac, click on your wifi symbol and go to Open Network Preferences. Here it shows what network you are connected to and the I.P. address you are connected with. Note that if you are using a phone to run the code, both the phone and your computer need to be on the same network. In you BackendURL.js enter this code with your local I.P. address.

export const URL= "http://your local I.P. goes here : port it runs on"

example

export const URL= "http://10.0.0.66:3000"

STEP TWO


Next we need to import this file into wherever you are doing a fetch call to your backend.

import {URL} from './BackendURL'

STEP THREE


We now need to replace the address in the fetch call from earlier. It should look something like this now

fetch(`${URL}/login`, {
 method: "POST",
 headers: {
 'Accept': 'application/json',
 'Content-Type': 'application/json'
      },
 body: JSON.stringify(value)
    })

STEP FOUR


Lastly we need to adjust the way we run our Rails server. If you run your server with "rails s" this only allows the the local machine to see this temp server you just booted up. We need it to accept all requests, even from an outside source. To do this run your server by typing in

 rails s --binding 0.0.0.0

FINAL NOTES


Keep in mind that every time to reconnect to a network you are going to have to update your local I.P. address. This is why we extracted the URL out into its own file. This way you only need to update your I.P. address in one spot instead of every location you have a fetch call.

4 views0 comments

Recent Posts

See All

Comments


bottom of page