如何在 React Native/Expo 中向本地主机发出获取请求?

odd*_*son 5 react-native fetch-api expo deno

我正在创建一个在后端使用Deno 的React Native/Expo 应用程序。我在后端创建了一个 API,可以在 localhost:4000 上本地运行。但是,当我尝试使用 fetch 调用 Expo 应用程序中的 API 时,我不断收到错误消息

[Unhandled promise rejection: TypeError: Network request failed] at node_modules/whatwg-fetch/dist/fetch.umd.js:535:17 in setTimeout$argument_0
Run Code Online (Sandbox Code Playgroud)

这是我设置后端的方法

import { Application } from "https://deno.land/x/oak/mod.ts";
import { oakCors } from "https://deno.land/x/cors/mod.ts";
import { APP_HOST, APP_PORT } from "./config.ts";
import router from "./routes.ts";
import _404 from "./controllers/404.ts";
import errorHandler from "./controllers/errorHandler.ts";

const app = new Application();

app.use(oakCors());
app.use(errorHandler);
app.use(router.routes());
app.use(router.allowedMethods());
app.use(_404);

console.log(`Listening on port:${APP_PORT}...`);
Run Code Online (Sandbox Code Playgroud)

以及我如何使用 fetch 调用 API

const App = () => {
  const getData = async () => {
    const response = await fetch("http://localhost:4000/something");
    const data = await response.json();
    console.log(data);
  };

  useEffect(() => {
    getData();
  }, []);

  return (
    ... 
  );
};
Run Code Online (Sandbox Code Playgroud)

笔记

  • StackOverflow 上的一些答案建议使用 fetchhttp://[IP_ADDRESS]:4000/something而不是 localhost。我已经尝试过了,但没有运气。
  • 我已经验证 API 正在运行。http://localhost:4000我可以在VSCode的迅雷客户端中成功调用它,并且在浏览器中也可以看到数据。

odd*_*son 6

我找到了这个问题的解决方案。我在物理设备上运行我的 Expo 应用程序,而我的服务器在我的计算机上的本地主机上运行。这是有道理的,我无法向我的设备上的本地主机发出请求,因为本地主机没有在那里运行。

我通过使用ngrok(一种将 localhost 转发到云 URL 的工具)并在应用程序中获取该 URL 来解决此问题。