16

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?

C.P.
  • 1,182
  • 3
  • 13
  • 32

2 Answers2

30

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/').

oblador
  • 2,954
  • 19
  • 15
  • I am making call to url but still getting same error. fetch('http://private-18642-test2979.apiary-mock.com/notes/1',{ method: 'get', 'headers': { 'Accept': 'application/json', } – Rajan Twanabashu Jul 05 '16 at 08:51
  • 1
    That is not really an URL, you need to add the protocol too. – oblador Jul 06 '16 at 09:59
13

Use the reverse command of the Android Debug Bridge tool (adb):

adb reverse <remote> <local> - reverse socket connections.
                               reverse specs are one of:
                                 tcp:<port>
                                 localabstract:<unix domain socket name>
                                 localreserved:<unix domain socket name>
                                 localfilesystem:<unix domain socket name>

For example:

adb reverse tcp:3333 tcp:3333

This makes localhost:3333 accessible from your device. You can also use different ports. For example:

adb reverse tcp:8081 tcp:3333

This will redirect the device port 8081 to the local port 3333.

Ricardo Stuven
  • 4,704
  • 2
  • 34
  • 36