28

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.

14 Answers 14

32

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

Sign up to request clarification or add additional context in comments.

4 Comments

this is fetch on react native issue, there is nothing with ipaddress.
Your answer helped me fix it.. it's not a permissions issue rather using localhost in the app
ipconfig getifaddr en0 is how to get your IP on mac. More information on that here link
tried your solution, but error still remains
9

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

1 Comment

I find this approach much simpler than finding using the IP address, which might be subject to change
6

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.

Comments

3

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

3 Comments

Hi, please double check your code before posting... Your address isn't a valid ip
hey, Why would i post my real IP??? I just showed the demo IP
Your local IP != the IP you should care about protecting - your internet accessible public IP. It's safe to post your 192.168.1.34 (or whatever) address. Mine is (10.0.2.20 right now). Unless you have good reason to need to protect your local IP you really need'nt worry. Not enough for 3 ? marks at least =)
2

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

Comments

2

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.

Comments

1

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.

1 Comment

ipconfig getifaddr en0 on mac
0

you should check the URL

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

NOT HTTPS

1 Comment

I already tried it doesn't change anything, I can't find the source of the problem
0

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.

Comments

0

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.

Comments

0

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.

Comments

0

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

Comments

0

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.

1 Comment

Thanks this made me remember that you must bundle the Root, Intermediate and leaf certificates together or it's not trusted by Android when making the HTTPS call
0

I was Simulating an Iphone on Xcode mac os, but i need it to test the camera, running expo go on my phone was giving me the error.

What Worked for me:
Run this command, in mac os -> ipconfig getifaddr en0 / in WIn -> ipconfig

It will give you, your public ip Address, then change localhost for your ip, example:

const URL = "http://{Your Public ip}:3000";

// example fetch
await fetch(URL + "/api/profiles")

✌️

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.