Stave
Stave

Reputation: 313

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 it throws 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.

-- 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.

Upvotes: 27

Views: 46370

Answers (13)

jgarcias
jgarcias

Reputation: 699

I also faced this error in Android simulator and physical device, using the fetch() API and this software versions:

"expo": "^50.0.15",
"react-native": "0.73.6",

and as some of the answers have stated, the solution in my case can be reduced to two things:

1- Don't use FormData objects to send data. Instead, use a standard JS object and apply JSON.stringify() to it when sending the request.

2- If you send the request successfully, using HTTP only, then you have some sort of problem with your SSL certificate. Make sure it has not expired, it is valid for your domain/subdomain name and it was issued by a valid CA.

Upvotes: 0

LeulAria
LeulAria

Reputation: 625

for me my docer server was running on 0.0.0.0 so used that instead of the localhost.

Upvotes: 0

quicky
quicky

Reputation: 11

This problem is typically because you're using HTTPS endpoint with a certificate which is not signed by a regular CA and by your private self-signed CA.

You can either create a valid signed certificate by a regular CA or add your private CA in the Certiticate Authority repository in your device.

Upvotes: 0

Bali Dinesh
Bali Dinesh

Reputation: 1

if you are using expo then you should check in your packages whether you have installed expo-dev-client and build your app via that then make sure you uninstall it before building the apk or .aab

then in my case it worked fine.

Upvotes: 0

lemario
lemario

Reputation: 596

This might be a wild shot but it might help someone. I was trying to use expo auth and the useAutoDiscovery() was not working. I was using the "export default App" type of init and changed it to const App = () => { and it started working.

Upvotes: 2

piyush yadav
piyush yadav

Reputation: 71

If your backend endpoints are correct and your request is successfully running in postman then you can try changing your endpoint in client side from localhost to ip address

In my Case from -> http://localhost:8000/signup to -> http://192.168.25.3838:8000/signup

Upvotes: 2

Ikechukwu Nicholas
Ikechukwu Nicholas

Reputation: 11

I had a similar issue. Apparently, the emulator does not understand or see 'localhost' as host. What I did: run ipconfig on your cmd, copy the ipv4 address, then use that to replace 'localhost' for your server host.

Upvotes: 1

Naadof
Naadof

Reputation: 517

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

Upvotes: 2

Roshinie Jayasundara
Roshinie Jayasundara

Reputation: 307

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.

Upvotes: 0

yukiyao
yukiyao

Reputation: 91

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

Upvotes: 7

Anton Makarov
Anton Makarov

Reputation: 644

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

Upvotes: 30

Shivam Chaudhary
Shivam Chaudhary

Reputation: 91

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.

Upvotes: 5

738
738

Reputation: 29

you should check the URL

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

NOT HTTPS

Upvotes: 0

Related Questions