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

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

问题描述

我正在创建一个 react-native 应用程序,我创建的其中一个组件包含一个属性,该属性是通过来自 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 manifest 获取 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 Store 部署的应用似乎具有 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

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

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