Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native: fetch request failed with error - TypeError: Network request failed(…)

I am developing a simple app using React Native. I am testing it on Android device. I have created a Node.js server to listen to the requests, it is running at http://localhost:3333/. Next, I am making a fetch request from index.android.js. Below is the code.

fetch('http://localhost:3333/', 
        {
            'method': 'GET',
            'headers': {
                'Accept': 'text/plain',                                     
            }
        }       
    ) 
.then((response) => response.text()) 
.then((responseText) => {
    console.log(responseText);  
}) 
.catch((error) => {
    console.warn(error);
}); 

The code for the request handler at node server is below

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
}); 
app.use(express.static('public'));
app.get('/', function(req, res){ 
    console.log('Request received for /');
    res.send("this is the response from the server");
    res.end();
});

But, the fetch request is not working. The error I get in the Chrome console is: TypeError: Network request failed(…).

How to make this work?

like image 474
C.P. Avatar asked Nov 28 '15 08:11

C.P.


People also ask

How do you solve Typeerror network request failed in react native?

THE TRICK THAT HELPED ME. It's just that simple! Start your app as usual but don't forget to give an IP address and a port, this will help you solve the Network Request Failed error. And on your mobile app, make sure to use the correct URL in your request.

What is network request failed?

Network request failed, this error occurs usually when api call failed or you have some internet issue. In android emulator, sometimes this error comes during debug mode but works fine when app use in release mode.

Why does my phone say network request failed?

Most of time , when network request failed error occurred, clearing the app cache will resolve the issue. So, To fix Instagram network request failed issue, clear Instagram app cache. To clear the Instagram App cache, For Android users, Go to settings >> Find Instagram App >> Tap on clear cache.

What is network request?

A network request is an HTTP request from your mobile app to a server-side application. The iOS Agent detects network requests when the underlying implementation is handled by the NSURLConnection or NSURLSession classes.


1 Answers

Since your Android device has an IP of its own, you need to point the URL to your computers IP address instead of just localhost. For example fetch('http://192.168.0.2:3333/').

like image 159
oblador Avatar answered Sep 18 '22 14:09

oblador