I am developing an Android app using React Native. I am testing my app on a Galaxy Nexus API 23 that is being emulated in Android Studio, running on a mac.
I wish to allow users to share information with each other. I am running a webserver with php and mysql, and I want the app to make requests to the server to share data between users.
I am trying to make a POST request to my development server using the Fetch API. My js code is below:
var AjaxEngine = {
test: function() {
return fetch('http://10.0.2.2/test.json')
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
return responseJson.movies;
})
.catch((error) => {
console.error(error);
});
}
};
called by AjaxEngine.test();
In my emulator I receive the following error:
ExceptionsManager.js:70 TypeError: Network request failed at XMLHttpRequest.xhr.onerror (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:23711:8) at XMLHttpRequest.dispatchEvent (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:9740:15) at XMLHttpRequest.setReadyState (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25157:6) at XMLHttpRequest.__didCompleteResponse (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25015:6) at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:25090:52 at RCTDeviceEventEmitter.emit (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:8977:23) at MessageQueue.__callFunction (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:7065:23) at http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:6969:8 at guard (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:6917:1) at MessageQueue.callFunctionReturnFlushedQueue (http://localhost:8081/index.android.bundle?platform=android&dev=true&hot=false&minify=false:6968:1)
test.json consists of:
{
"message":"hello world"
}
The request is successful when I replace 'http://10.0.2.2/test.json' with 'http://facebook.github.io/react-native/movies.json', so the function itself is ok.
'http://localhost/test.json' and 'http://127.0.0.1/test.json' both load in a web browser, curl, and wget. I have also tried replacing the 10.0.2.2 with 127.0.0.1. I have also tried using my local ip (129.xxx.x.x)
What do I need to do to make these requests work? How do I access my development server running on localhost from the emulated android app?