Home > Mobile >  Do React Native proxys work differently to vanila react proxys?
Do React Native proxys work differently to vanila react proxys?

Time:12-01

I'm trying to fetch data from a API running locally on port 5000 my device. From working on React web apps I'm used to setting the proxy in package.json like this:

"proxy": "https://localhost:5000"

Now I try to fetch something from the API like this:

fetch("/colours", {
            method: "GET",
            headers: {
                "Content-Type": "application/json;charset=utf-8",
            }
        })...

Sadly if I now run my application on my browser it still says that it sends the request to http://localhost:19006/colours. The responds contains HTML for a reload button.

I also checked on my APIs console, no request ever arrives there. I have tried the usual tricks of deleting package-lock.json and node_modules and installing again.

Is my approach to API requests fundamentally wrong for React Native?

CodePudding user response:

Yes, network requests work differently in React Native, because it is not a browser-based framework. I presume fetch is going to localhost:19006 because that's the port Metro is running on.

The simplest way to get what you want, I think, is to define the URL in code. More commonly, it's set into your environment, and used through something like react-native-config.

Here's an example of fetching with the URL defined inline:

const API_URL = 'http://192.168.X.X:5000'

const options = { ... }

fetch(API_URL   '/colors', options)
  .then(console.log);

NB: don't use localhost, as it will only work in the iOS simulator (and maybe in a browser). Use your local IP address instead. This is because the iOS simulator is the only "device" that shares your machine's network config. The Android emulator, or any real device, will not.

  • Related