如何在React Native/Expo中向localhost发出获取请求



我正在创建一个在后端使用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

以下是我如何设置后端

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}...`);

以及如何使用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 (
... 
);
};

注意

  • StackOverflow上的一些答案建议获取http://[IP_ADDRESS]:4000/something而不是localhost。我试过,但没有成功
  • 我已经验证了API是否有效。我可以在VSCode的Thunder客户端中成功调用它,也可以通过在浏览器中转到http://localhost:4000来查看数据

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

我通过使用ngrok解决了这个问题,ngrok是一种将本地主机转发到云URL的工具,并在应用程序中获取该URL。

使用设备的本地IP分配,如:http://192.168.20.109:port/api/x

使用命令"查找"找到本地IP;ipconfig";在windows或linux 中的ifconfig中

最新更新