Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native fetch a local server using a proxy

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)
like image 200
siddrajpoot Avatar asked Feb 23 '19 09:02

siddrajpoot


People also ask

How do I use a proxy server in React?

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.

Where do I put proxy in package json in React?

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 .

Why you should use a proxy server with create React app?

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.

What is proxy in React native?

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.


1 Answers

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.

like image 121
duan Avatar answered Oct 02 '22 22:10

duan