从Expo App调用本地托管的服务器 [英] Calling locally hosted server from Expo App

查看:129
本文介绍了从Expo App调用本地托管的服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个本机应用程序,并且我创建的组件之一包含一个属性,该属性通过来自http请求的数据填充.

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.

现在,我正在从笔记本电脑托管服务器,但是我正在使用Expo应用程序在手机上测试该应用程序.由于这是两个单独的设备,因此 http://localhost:3000 调用无法正常工作,因此我无法确定是否我的组件无法正常工作.

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.

我是否可以通过任何方式在笔记本电脑上运行服务器并进行设置,以使来自Expo应用程序中的http请求到达服务器?

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?

推荐答案

您可以使用Expo清单在运行时获取IP地址:

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`;

这会将api常量设置为处于开发模式的本地开发计算机的地址以及生产中使用的任何地址.请注意,通过App Store/Play商店部署的应用似乎具有packagerOpts undefined.这就是为什么我们还有其他typeof条件的原因.在那种情况下,我们假设它是生产版本.

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.

有关清单的更多信息: https://docs.expo.io/versions/latest/workflow/how-expo-works/#expo-development-server

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

这篇关于从Expo App调用本地托管的服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆