'React Native / Expo : Fetch throws “Network request failed”

I saw several posts on the subject but without result. I have on the one hand a form which collects information (name, first name etc) then saves it in database (mongodb). Everything works when I use postman to send my information via the route / signup, i can see my new user in mongodb. but when i'm starting the app on Expo he throw me "Network request failed".

Frontend fetch :

submitForm = () => {
  var signupData = JSON.stringify({
    first_name: this.state.firstName,
    last_name: this.state.lastName,
    email: this.state.email,
    password: this.state.password
  });

  fetch(`https://localhost:3000/signup`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: signupData
  })
    .then(response => {
      console.log(response);
      return response.json();
    })
    .then(data => {
      if (data.result) {
        this.props.handleUserValid(
          this.state.firstName,
          this.state.lastName,
          this.state.email,
          data.user.token
        );
        this.props.navigation.navigate("Account");
      }
    })
    .catch(error => {
      console.error(error);
    });
};

And Backend route :

router.post("/signup", function(req, res, next) {
  var salt = uid2(32);

  console.log("Signup is running...");
  const newUser = new userModel({
    first_name: req.body.first_name,
    last_name: req.body.last_name,
    email: req.body.email,
    password: SHA256(req.body.password + salt).toString(encBase64),
    token: uid2(32),
    salt: salt
  });
  newUser.save(function(error, user) {
    console.log("LOG: user", user);
    res.json({ result: true, user });
  });
});

module.exports = router;

And here is a screenshot of the error

enter image description here

Again when using Postman, the fetch is working good, my console log is printed and the user added to my data base. Thanks for the help.

-- EDIT --

I launched the application in a web browser via Expo and everything works perfectly. My sign in / sign up pages and my account page. But on my phone it's not working (IOS), it's a network problem from my phone (maybe a certificate problem, wrong IP ?)

if you have an idea i'm interested, i've been stuck on it for 2 days



Solution 1:[1]

Had the same issue with React-native Expo and Python Django back-end. The problem is about a conflict between an emulator localhost and server localhost. Your back-end-server might be ruunning on 127.0.0.1:8000, but an emulator can't find this.

In terminal find your Ipv4-Address with a command 'ipconfig'. For ex., it will be 192.138.1.40

After this put it into your fetch ( 'http://192.138.1.40:8000/').
And what is also important - run your back-end-server with the same host and port.
On python Django for example:

py manage.py runserver 192.138.1.40:8000

On Django you will also need to add ALLOWED_HOSTS = ['192.138.1.40'] in settings.py

Solution 2:[2]

I had the same issue with Expo: fetch error. For my backend. I use json-server to mock API data. In my case, the json-server runs on http://localhost:3000/playlist

Instead of fetch("http://localhost:3000/playlist"), I did fetch(http://10.0.2.2:3000/playlist), then it worked. Using the Android emulator, it could not find the server's address.

For the reason why using 10.0.2.2, check here. why do we use 10.0.2.2 to connect to local web server instead of using computer ip address in android client

Solution 3:[3]

Instead of 'localhost', while using expo, use your device's (computer's) IP address (http://192.168.x.x:3000/'signup'). This method worked for me. Make sure that your PC and mobile are connected to the same network. Type ipconfig/all in the command prompt to find IP address.

Update:

Seems like this was my problem coupled with my roommates hogging the wifi bandwidth. Slow internet connection may also be a problem. ATB with your problem.

Solution 4:[4]

you should check the URL

  • https://localhost:3000/signup (X)
  • http://localhost:3000/signup (O)

NOT HTTPS

Solution 5:[5]

If anyone facing this issue with a hosted backend server this is for your knowledge.

But still I faced the below issue.

 Network request failed at node_modules\whatwg-fetch\dist\fetch.umd.js:535:17 in setTimeout$argument_0
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:130:14 in _callTimer
at node_modules\react-native\Libraries\Core\Timers\JSTimers.js:383:16 in callTimers
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:416:4 in __callFunction
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:109:6 in __guard$argument_0
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:364:10 in __guard
at node_modules\react-native\Libraries\BatchedBridge\MessageQueue.js:108:4 in callFunctionReturnFlushedQueue

After some research I found that this is because the slow response time of the server. The network request failed due to the timeout.

So Before testing your app with the backend server, send some requests from the web(or any other way) and up your server. Because some servers get inactive after some time. Make sure you have a good connection.

Solution 6:[6]

I had the same issue - what worked for me was to:

  1. Run my local server on host 0.0.0.0
  2. Go to network preferences and find my LAN IP address (e.g. 192.168.1.1)
  3. Replace the host in my url in the mobile app with the LAN IP (e.g. http://192.168.1.1:3000/signup)
  4. Reload and test

For anyone using Serverless, I used this command to run on 0.0.0.0

ENV=local serverless offline -s local -o 0.0.0.0

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Dharman
Solution 3
Solution 4 738
Solution 5 Roshinie Jayasundara
Solution 6