Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

react native - Calling locally hosted server from Expo App

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 I am hosting the server from my laptop, however I am testing the app on my phone using the Expo app. Since these are two separate devices, the http://localhost:3000 calls are not working and thus I can not tell whether or not my component is properly working.

Is there any way for me to run the server on my laptop and set it up so that the http requests from within the Expo app reach the server?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...