How to make a fetch request to localhost in React Native/Expo?
Asked Answered
B

2

7

I'm creating a React Native/Expo app that uses Deno on the backend. I've created an API in the backend that I can run locally on localhost:4000. When I try to use fetch to call the API in the Expo app, however, I keep getting an error

[Unhandled promise rejection: TypeError: Network request failed] at node_modules/whatwg-fetch/dist/fetch.umd.js:535:17 in setTimeout$argument_0

Here is how I set up the backend

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

And how I use fetch to call the 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 (
    ... 
  );
};

Note

  • Some answers on StackOverflow suggest fetching http://[IP_ADDRESS]:4000/something instead of localhost. I've tried that with no luck.
  • I've verified that the API is working. I can call it successfully in VSCode's Thunder Client and I can also see the data by going to http://localhost:4000 in the browser.
Burkes answered 29/6, 2022 at 8:40 Comment(4)
I bet you are on android =) Use 10.0.2.2 from your app if soCattle
Thanks for taking the time to comment @JeanJacquesGourdin. I'm not on Android, I'm on a physical iOS device.Burkes
Ah ok, may be try #67395107 from what I see, you should use exp and not httpCattle
You generate code snippet for fetch in Thunder Client and then compare your codeSwigart
B
10

I found a solution to this issue. I'm running my Expo app on a physical device while my server is running on my computer, on localhost. It makes sense that I'm unable to make requests to localhost on my device, because localhost is not running there.

I fixed this issue by using ngrok, a tool that forwards localhost to a cloud URL, and fetching that URL in the app.

Burkes answered 4/7, 2022 at 11:29 Comment(3)
kudos for mentioning ngrok. This is a game changerLovelace
Can you elaborate. I have the same issue as you did and I have tried ngrok.Surplus
ngrok works like magic!! thanks for sharingWhortleberry
H
6

Use the local IP assign to your device, like: http://192.168.20.109:port/api/x

find the local IP using the command "ipconfig" in windows or ifconfig in linux

Herbart answered 9/1, 2023 at 18:8 Comment(1)
If you're using macOS, you may need to temporarily disable the firewall.Barclay

© 2022 - 2024 — McMap. All rights reserved.