In my react native app I am trying to perform a fetch
to my local backend server. In my package.json
I have put "proxy": "http://localhost:3000"
.
My fetch looks like
fetch('/')
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log)
It catches an error
[TypeError: Network request failed]
When I remove the proxy and manually enter the address in the fetch it works and my server receives a GET request.
fetch('http://localhost:3000')
.then(response => response.json())
.then(json => console.log(json))
.catch(err => console.log)
Proxy Setup with Create-React-App All you have to do is add a proxy field to your package. json file, like shown below. "proxy": "http://localhost:3000", This line instructs the development server to proxy any unknown requests to your API server in development mode.
To configure the proxy, you'll need to add the following line to your package. json . Then, in your React app, you can make API requests by using relative paths. For example, http://localhost:8000/api/todos becomes /api/todos .
Proxy servers can assist in redirecting requests to APIs without having to go via the browser's default request options, which helps to evade several cross-origin limitations. Second is fetching data from cross-origin APIs that don't support CORs in web browsers.
In general, A proxy or proxy server serves as a gateway between your app and the internet. It's an intermediate server between client and servers by forwarding client requests to resources. In React, we often use this proxying in the development environment.
Two points here:
Set proxy
in package.json
is a feature of create-react-app, which wraps webpack dev server's proxy. react-native uses Metro instead of Webpack as bundler and it does not support setting up a local proxy.
Different from the web, http client in react-native has no current host
. So if you use fetch('/')
, it won't know which domain or ip address to send request to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With