Search code examples
androidnode.jsreact-nativeexpomobile-development

Can't send HTTP requests to Localhost Backend from React Native Mobile App


First day of 2022~! Learning mobile app dev is giving headaches. It can't be this difficult to set up. I've already lost 6 hours. Please help!

Situation My dev environment runs in Ubuntu via VMWare hosted on Windows 10. Within this environment I have:

  • a Node/express backend API running on localhost that works fine when tested with Postman/browser
  • a default react native app made and run via Expo. I test this app from my Android phone by reading the QR code Expo/metro provides, served via Tunnel

Desired Behaviour:

  • the React Native mobile app should be able to communicate with the backend API

Error:

Network Error
at node_modules/axios/lib/core/createError.js:15:17 in createError
at node_modules/axios/lib/adapters/xhr.js:114:22 in handleError
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:609:10 in setReadyState
at node_modules/react-native/Libraries/Network/XMLHttpRequest.js:396:6 in __didCompleteResponse
at node_modules/react-native/Libraries/vendor/emitter/_EventEmitter.js:135:10 in EventEmitter#emit

Axios Post Request from React Native (abbreviated)

axios.post('http://localhost:5000/user/login', some-data)

Attempted Resolutions

  • replaced 'localhost' with variations of 10.0.2.2 and 127*
  • connecting via Expos (LAN or local instead of tunnel) but could not connect (timeout error)
  • playing with Ubuntu ufw firewall settings (disable, allow port)
  • ignoring all together by installing Android Studio to emulate but was told my device does not support SVM or at-x hardware virtualization which lead me down another rabbit hole

Solution

  • So I realize what I did wrong.

    When I ran adb reverse I used the ports that were used in tutorials and stackfoverflow questions (because often times these are defaults). But you need to use the port where your backend API is listening to.

    For anyone else stuck the complete guide is: If your backend API is listening on 'localhost:5000' and if your react native app is running via expo on Local (it will say Metro is listening on 127* in the terminal, or 10* if set to LAN) Then in the API request replace localhost with the the IP listed in expo above (127 or 10) And in the terminal 'adb reverse tcp:5000 tcp:5000'

    In Summary:

    1. adb reverse the port that your backend api is listening on
    2. swap localhost for the ip listed by Metro in the terminal when you start react native with expo