siddrajpoot
siddrajpoot

Reputation: 183

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)

Upvotes: 8

Views: 3432

Answers (2)

duan
duan

Reputation: 8885

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.

Upvotes: 7

Mayank Pandav
Mayank Pandav

Reputation: 455

hello you can use your network IP Address for using local server like instead localhost change with your Ip address and you can call your server e.g, http://192.xxx.x.xxx:3000

Upvotes: 0

Related Questions