Network request failed React native fetch (Android) - android

I have a case when fetching SSL API I get the request fetched successfully on IOS
But on android I have an exception as following
TypeError: Network request failed
at XMLHttpRequest.xhr.onerror (index.android.bundle:12910)
at XMLHttpRequest.dispatchEvent (index.android.bundle:13813)
at XMLHttpRequest.setReadyState (index.android.bundle:15406)
at XMLHttpRequest.__didCompleteResponse (index.android.bundle:15262)
at index.android.bundle:15357
at RCTDeviceEventEmitter.emit (index.android.bundle:3851)
at MessageQueue.__callFunction (index.android.bundle:2090)
at index.android.bundle:1948
at MessageQueue.__guard (index.android.bundle:2062)
at MessageQueue.callFunctionReturnFlushedQueue
(index.android.bundle:1947)
Any way to solve this issue?
Only SSL fetch on android fail. If i fetched HTTP API it works
Edit #1
React-native version:0.44.3
Android emulator version: 7.0
Tested devices: Samsung galaxy j7 prime(Real device) and pixel 2 XL (emulator)
Edit #2
this the code
try {
let url = "https://URL_HERE";
console.log(url);
let bodyData = {
user: {
email: user.email//...etc
}
};
let response = await fetch(url, {
headers: {
'Content-Type': 'application/json'
},
method: 'post',
body: JSON.stringify(bodyData)
});
res.code = response.status;
if (res.code === 200) {
let responseJson = await response.json();
}
} catch (error) {
console.error(error);
}
TIA

Related

Fetch DELETE method on Android (React Native)

I make several requests from a React Native app to an API. Every request works fine both on iOS and Android except the DELETE method that does not work on Android. The call is correctly made, it goes through the API and the objects are deleted. But instead of getting the response, the call falls under the catch statement with [TypeError: Network request failed]. This does not happen in iOS.
Some people with the same problem were missing 'Content-Type': 'application/json' on the request headers which is not my case.
This is happening both locally, in testing and production stages (using an ip instead of localhost will do nothing).
The request is also successfully performed in Postman.
What can it be?
React Native 0.63.5
export const deleteApi = async (api: string, body?: any) => {
const userResponse = await getUserCredentials();
const authState = await getAuthState();
let response = await fetch(api, {
method: 'DELETE',
headers: await getHeaders(userResponse, authState),
body: JSON.stringify(body)
});
if (response.status === UNAUTHENTICATED_CODE)
response = await interceptor(response, userResponse, {
api: api,
method: 'DELETE',
body: body
});
return response;
};
leaveClass = async (
uuid: string,
onSuccess: () => void,
onFailure: (error: string) => void,
) => {
this.setLoading(true);
try {
const api = LEAVE_CLASS_API_PREFIX + uuid + LEAVE_CLASS_API_SUFFIX;
const response = await deleteApi(api);
if (response.status === SUCCESS_STATUS_CODE) {
onSuccess();
}
else {
const jsonResponse = await response.json();
if (jsonResponse.detail) onFailure(jsonResponse.detail);
else onFailure(translations.SOMETHING_WENT_WRONG);
}
} catch (error) {
console.log('leaveClass error: ', error);
}
this.setLoading(false);
};
You can use a network plugin for Flipper (https://fbflipper.com/docs/setup/plugins/network/), copy your request from it as a curl, and try to perform it from your terminal or postman. If it has the same error, the problem is not in React Native.

React-Native (Android) : Request failed with status code 403 - bscscan api testnet

Please help me, I'm so stuck on this problem: I'm making an request BSCSCAN-API-TESTNET with Axios on React Native and the request is working correctly only within the iOS, but it is not working with the Android (403 Forbidden response).
My URL request: https://api-testnet.bscscan.com/api?module=account&action=txlist&address=0x400ee0c820144c8bb559ace1ad75e5c13e750334&sort=desc&apikey=P3A263376TPJHKQ5IXUD4VHUNFQKDJB4G5
I updated the apiKey so don't mind it.
My code: (IOS: oke, android: throw error 403)
try {
const url =
'https://api-testnet.bscscan.com/api?module=account&action=txlist&address=0x400ee0c820144c8bb559ace1ad75e5c13e750334&sort=desc&apikey=P3A263376TPJHKQ5IXUD4VHUNFQKDJB4G5';
const response = await axios.get(url);
} catch (error) {
throw error;
}
Setting the user agent helped me solve the 403 issue.
try {
const url =
'https://api-testnet.bscscan.com/api?module=account&action=txlist&address=0x400ee0c820144c8bb559ace1ad75e5c13e750334&sort=desc&apikey=P3A263376TPJHKQ5IXUD4VHUNFQKDJB4G5';
const response = await axios.get(url, {headers: { "User-Agent": "Mozilla/5.0" }});
} catch (error) {
throw error;
}

ionic3 error on android when calling GET HTTP

In Ionic3 I installed import { HttpClientModule } from '#angular/common/http'; and in my code I'm trying to call below url :
testHTTP(){
this.httpClient.get("https://api.upcitemdb.com/prod/trial/lookup?upc=5425016921463").subscribe(
data => {
console.log('Data : ', data);
this.lookup = data["items"][0].title;
}, err => {
console.log('Error : ', err);
this.lookup = JSON.stringify(err);
});
}
but every time it fails with :
{"headers":{"normalizedNames":{},"lazyUpdate":null,"headers":{}},"status":0,"statusText":"Unknown Error","url":null,"ok":false,"name":"HttpErrorResponse","message":"Http failure response for (unknown url): 0 Unknown Error","error":{"isTrusted":true}}
When I click on the button calling testHTTP on Chrome, I get a CORS error with this object (but I can deactivate CORS and get the real response).
How do you setup ionic http for the get to work please ?
You should use a XMLHttpRequest. And dont forget the Headers.
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.upcitemdb.com/prod/trial/lookup?upc=5425016921463", true);
//Really important to set this header
xhr.setRequestHeader("Access-Control-Allow-Origin","http://localhost:8100");
xhr.onreadystatechange = function() {
if(xhr.readyState == xhr.DONE) {
let ResponseFromRequest = xhr.response //Response from your request
}
}
xhr.send(null);

How to setup fetch for React Native Android using gzip?

My React Native app had been working fine on both iOS and Android but recently it gives Network request failed error on Android when the response is long.
I found out if I set the request's header to 'Accept-Encoding': 'gzip',, I was able to log response, but it only contains header and such:
{
type:'default',
status:200,
ok:true,
statusText:undefined,
headers:{
map:{
date:'Mon, 27 Aug 2018 18:39:23 GMT',
'content-type':'application/json',
'content-length':'215',
'content-encoding':'gzip',
'cache-control':'no-cache'
}
},
url:'http://test.essaybot.com/essay/list',
_bodyInit:'',
_bodyText:''
}
This is how I setup the fetch request:
const URLENCODED_HEADER = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Accept-Encoding': 'gzip',
'Content-Encoding': 'identity'
}
async function getEssayList() {
try {
let response = await fetch(SERVER_URL+'/essay/list', {
headers: URLENCODED_HEADER,
credentials: 'include',
});
let responseJson = await response;
console.log("[getEssayList]=======>", responseJson)
} catch(error) {
console.error(error);
throw error;
}
}

Network request in react native fails after two minutes

I am having some trouble using couchdb in react native. See code below :
const urlcouchdb = 'http://192.168.58.1:5984';
export const login = async (name, password) => {
const response = await fetch(`${urlcouchdb}/_session`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
name,
password,
}),
}).catch(function(error) {
console.log("error = " + error);
return error;
});
if (
response.headers &&
response.headers.map['set-cookie'] &&
response.headers.map['set-cookie'][0]
) {
await AsyncStorage.setItem(
'cookiecouchdb',
response.headers.map['set-cookie'][0],
);
}
return response.json();
}
At first, I was using my localhost IP (127.0.0.1), and I was getting this error : TypeError: Network request failed.
After some researches, I've figured out I'd better change it to the IP address of system. I thought my problem was solved, because I was not getting the error anymore, but it turned out that I was still getting the same error, but two minutes (approximatly), after doing the request!
It's very annoying to wait two minutes every single time I try to solve it. Do you have any idea why my request fails?
Just to let you know : The name and password I send to login function are correct. Also, I am testing on my android device, using expo.

Categories

Resources