Calling locally hosted server from Expo App

后端 未结 7 723
无人共我
无人共我 2020-12-08 20:26

I am creating a react-native app and one of the components I have created contains a property which is populated through data coming from an http request.

Right now

相关标签:
7条回答
  • 2020-12-08 20:50
    import Constants from "expo-constants";
    
    const { manifest } = Constants;
    
    const uri = `http://${manifest.debuggerHost.split(':').shift()}:4000`;
    
    0 讨论(0)
  • 2020-12-08 20:51

    You can get the IP address at runtime using the Expo manifest:

    import Constants from "expo-constants";
    const { manifest } = Constants;
    
    const api = (typeof manifest.packagerOpts === `object`) && manifest.packagerOpts.dev
      ? manifest.debuggerHost.split(`:`).shift().concat(`:3000`)
      : `api.example.com`;
    

    This will set api constant to the address of your local development machine in development mode and to whatever address you use in production. Note that apps deployed through App Store / Play Store seems to have packagerOpts undefined. That's why we have additional typeof condition. In that case we assume it's production build.

    More about the manifest here: https://docs.expo.io/versions/latest/workflow/how-expo-works/#expo-development-server

    0 讨论(0)
  • 2020-12-08 20:56

    For the life of me, I could not get any solution that I found (including all the ones on this page) to work. I spent a couple days trying. Finally, I just gave up and worked around this whole problem by using localtunnel and exposing my service running on localhost:8080 to the web. Worked first try when calling it from my expo app. Maybe not the greatest long-term solution, but not so bad, either. I hope this helps someone else!

    0 讨论(0)
  • 2020-12-08 20:59

    You should replace the http://localhost:3000/ address with the ip address of your computer.

    On windows, open a prompt and type ipconfig, check the line of your network interface and get the address IPV4, should look like 192.168.1.20. Then you can make your calls with fetch and an url looking like htt://192.168.1.20/routname.

    By the way, your computer (server) and your device must be on the same local network. Wifi and lan shares the same network.

    0 讨论(0)
  • 2020-12-08 20:59

    I tried some of it and it didn't work, finally simply used ngrok

    0 讨论(0)
  • 2020-12-08 21:02

    To add to Tadeusz's answer, in the current version of Expo (I'm on 32.0.0 right now), you would import Constants rather than Expo (even though the constants are referenced in the docs as Expo.Constants.manifest), so it would look like

    import { Constants } from 'expo';
    const { manifest } = Constants;
    

    Also, prepending the generated address with the protocol seems to be a must to make it all work.

    0 讨论(0)
提交回复
热议问题