I have an issue with a fetch (api call) on react native, when i have a low connection or temporarly lost connection.
My function :
async function getlastcursor(att){
const url=base_url+"/lastcursor;
const formData = new FormData();
formData.append('att', att);
let result="";
try {
result=fetch(url, {
method: 'POST',
headers:{
'content-type':'multipart/form-data'
},
body: formData,
}).then((response) => response.json())
} catch (error) {
}
return result;
}
If log can be help to debug me :
Possible Unhandled Promise Rejection (id: 23):
TypeError: Network request failed
onerror#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:26748:31
dispatchEvent#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:32302:31
setReadyState#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31386:33
__didCompleteResponse#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:31213:29
emit#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:3316:42
__callFunction#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2648:49
http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2361:31
__guard#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2602:15
callFunctionReturnFlushedQueue#http://localhost:8081/index.bundle?platform=android&dev=true&minify=false:2360:21
callFunctionReturnFlushedQueue#[native code]
I would like to retry automatically when i have a Network request failed (which is when connection is low or temporarly lost).
What can i do to make it ? Use Promise class?
Thanks you
Related
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.
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);
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
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.
I got this error in my application ( react-native ) when internet connection is lost.
When i start the app on offline mode, Initial component renders, try to execute the query, app crashes.
it works perfect when my app is connected with internet. But my application crashes when its not. How can i handle this error?
ExceptionsManager.js:71 "Unhandled error Network error: Network request failed Error: Network error: Network request failed at new ApolloError"
import ApolloClient, { createNetworkInterface } from 'apollo-client';
import { AsyncStorage } from 'react-native';
import {SubscriptionClient, addGraphQLSubscriptions} from 'subscriptions-transport-ws';
const wsClient = new SubscriptionClient('wss://172.20.32.6:5000', {
reconnect: true,
connectionParams: {
accessToken: 'jka sdhkjashd jkashdjk ashdas'
}
});
const networkInterface = createNetworkInterface({
uri: 'http://172.20.32.6:8000/graphql',
opts: {
credentials: 'same-origin'
}
});
const networkInterfaceWithSubscriptions = addGraphQLSubscriptions(
networkInterface,
wsClient
);
const client = new ApolloClient({
dataIdFromObject: o => o.id,
networkInterface: networkInterfaceWithSubscriptions
});
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // Create the header object if needed.
}
// get the authentication token from local storage if it exists
AsyncStorage.getItem('sessionToken').then((token) => {
req.options.headers.Authorization = token ? `${token}` : null;
next();
}
);
}
}]);
export default client;
To avoid this very unhelpful error, add something like this at the top of the component that renders your query result.
if (data && data.error) {
return (
<View>
<Text>{JSON.stringify(data.error)}</Text>
</View>
)
}
more info of dealing with error can be found in this github issue
https://github.com/apollographql/react-apollo/issues/604