React Native Post Request via Fetch throws Network Request Failed
This React Native's error is rather useless, so you need to get the actual underlying error first. The most straightforward way is to write a small native program that would just perform the same query using HttpsURLConnection
.
For me the actual error was java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
which has a well known solution: https://developer.android.com/training/articles/security-ssl.html#MissingCa
This is quite likely your case also, given that the browsers and Postman have no problem with the request. To check it run openssl s_client -connect XXreachable-domainXX.de:443 -showcerts
. If there are certificate errors, fix them first, it could spare you time writing the native program.
Edit: actually the easiest way to see all underlying android errors for react native is simply running 'adb logcat' in terminal
None of the other answers helped me.
The problem was headers
:
Old header:
fetch(API_HOST, {
method: 'POST',
headers: {
Accept: 'application/json'
},
body: JSON.stringify(data),
Updated header:
fetch(config.API_HOST, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json' // I added this line
},
body: JSON.stringify(data),
Developing with Windows OS/PHP built-in server/react-native Android on device:
- check server local IP address (
ipconfig
), e.g. 172.16.0.10 - in react-native
fetch
use this URL and proper port (fetch('http://172.16.0.10:8000/api/foo)
) - run PHP built-in server with this specific IP instead of the localhost:
php -S 172.16.0.10:8000 ...
- turn off Windows firewall for the private networks
That fixed the connection problem between Android phone and the local server for me.
If you have had this error and you are sure everything works well and you are running an emulator, simply close your emulator and fire it up again.
It should run now.
This usually happens after you have hibernated your system for a while