How to resolve React Native Android Axios Network Error? - android

I was using Axios post request to do an API call. It was working fine with iOS but for Android, it was shown Network Error 400.
When I try encoded URL with encodeURIComponent like the following and API was successful with status 200.
return await axios.post(encodeURIComponent(url),JSON.stringify(data), config)
.then(({ data }) => {
return { success: 1, data };
})
.catch(error => {
console.log('error', error)
return { success: 0, error: error.message };
});

Since, there little details concerning the problem. I will say make sure the Content-Type header is set. It's always necessary on android.

Related

Ionic get call not working in real android device (no error in console too)

I am on ionic 4. And I am using httpClient package to make the http calls. Nothing is happening when I hit the function. And I am not getting error in console too.
I know there are many answers for the same issue, but none of them worked for me.
I am importing as import { HttpClient, HttpHeaders } from '#angular/common/http';
My http service as below
this.http.get(fullurl)
.map(data => {
this.loading.dismiss();
console.log(data);
if(msg!="" && msg.length >= 0){
this.loading.dismiss();
}
The httpClient.get is an Observable. Which means you have to use like this:
import { HttpClient } from '#angular/common/http';
constructor(private http: HttpClient) { }
this.http.get(fullUrl)
.subscribe((data) => {
// Success handler
}, (error) => {
// Error handler
});

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.

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.

React Native fetch, unexpected token

I'm trying to call a simple REST service with fetch api in React Native. I'm running the app on Android.
When I call await response.json() I get
Unexpected token � in JSON at position 0
, I tried also with await response.text(), and I get this text as result:
��Mn�0��B�[C�bn�u��?#�+�bLR�ҌBR.�
�����H�ծ�͛�#?>�g���t�%{���Z��؄u�>fs0]����H��'&��u�Z}��y�Z��2����i�d�G�>����R����6LL{j�j�7\���������d���L.���gٲXv�Lf��g�%T�~�\z�U8E܀���ڭ�c��#[G�;�T�������{�*�9�)��a½
���0�组V:ϒ���/�K��3�ݝ����W: c�^UV#�B�7�#�v
�+WG��#YL�|Ġ>q�=#�J}�3=��Q�]Հup^E�0 ^d'Ա
�^���b�.��2,��g2��R<���_rpV:!��<��^>�����{�e�#7m���nA�;n�������l�o�u��kW���r���
This is the code I'm using:
export function fetchMenu() {
return async(dispatch) => {
try {
dispatch(menuRequest(true));
console.log(Institucion.aplent);
var response = await fetch('http://<page_url>/api/moviles/personalizacion', {
compress: true,
headers: {
'aplentId' : Institucion.aplent,
'Accept-Encoding' : 'gzip,deflate'
}
});
console.log(response);
if(!response.ok) throw Error(response.statusText);
var data = await response.json();
console.log('Data:', data);
dispatch(menuSuccess(data));
}
catch(ex) {
console.log(ex);
dispatch(menuFailure(ex));
}
};
}
Note: I've changed the url to for security reasons, but I have the correct url in code.
I've tried with and without the Accept-Encoding header, the same result.
EDIT
If I disable deflate compression inside my REST API (on the server) it works ok, doesn't fetch support deflate compression?
Add these headers to the fetch call to ensure you receive JSON:
'Content-Type': 'application/json',
'Accept': 'application/json',
I would suggest seeing if it works without explicitly setting compression.
If you don't set the Accept-encoding header, react native should automatically zip and unzip it. So probably let it handle it. Instead try changing it to Accept header
export function fetchMenu() {
return async(dispatch) => {
try {
dispatch(menuRequest(true));
console.log(Institucion.aplent);
var response = await fetch('http://<page_url>/api/moviles/personalizacion', {
headers: {
'aplentId' : Institucion.aplent,
'Accept' : 'application/json'
}
});
console.log(response);
if(!response.ok) throw Error(response.statusText);
var data = await response.json();
console.log('Data:', data);
dispatch(menuSuccess(data));
}
catch(ex) {
console.log(ex);
dispatch(menuFailure(ex));
}
};
}
It was a server side issue, I changed the compression algorithm of the api, and it works well

Angular2 custom request

I am using a custom HTTP request class for adding a Authorization Header to all of my requests, this works fine on almost every android device. Wired thing now is that I got some customer complaints that they are getting the 'No internet connection' error although they have a working network connection (other apps work and the errors are transmitted to the Sentry servers also).
As I am using Sentry error tracking I found out that these customers are all getting the error because the timeout error is thrown after 10 seconds for the first request at app start.
I guessed that something has to be wrong with this request so I built an alpha version for a limited number of users to track down the error (I send the options of every request to Sentry), but the requests look fine.
Next guess was that something is wrong with cordova-plugin-nativestorage on these devices but as I am catching them it should at lease return an empty token. No clue how to fix it right now. Any advice is appreciated!
export class CustomRequest {
apiToken: string = '';
constructor(private http: Http) { }
protected request(options: any): Observable<any> {
// If Native Storage doens't find a token, return an empty
let errorNativeStorage$ = function (): Observable<any> {
return Observable.of({ Token: '' });
};
// Get Token form Native Storage
let token$ = Observable.fromPromise(NativeStorage.getItem('JWT'))
.catch(errorNativeStorage$);
// Handle request errors
let genericError$ = function (error: Response | any): Observable<any> {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.error(errMsg);
Raven.captureException(error, { extra: { errorMsg: errMsg } });
return Observable.of({
Errors: { General: 'No internet connection.' }
});
};
// the request
let request$ = (options) => {
return this.http.request(new Request(options))
.retryWhen(error => error.delay(1000))
.timeout(10000, new Error('timeout'))
.map((res: Response) => res.json())
.catch(genericError$);
};
// get the token and build request
return token$
.map(jwt => {
if (options.body) {
if (typeof options.body !== 'string') {
options.body = JSON.stringify(options.body);
}
options.body = options.body.replace(/ /g, '').replace(/\r?\n|\r/g, '');
}
options.headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded, application/json'
});
if (jwt.Token) {
options.headers.append('Authorization', `Bearer ${jwt.Token}`);
}
Raven.captureMessage('request options', { level: 'info', environment: 'live', extra: options });
return options;
})
.switchMap(options => request$(options));
}
}
I am using:
Ionic 2.0.0-beta.11
Angular 2.0.0-rc.4
Most recent version of NativeStorage plugin from github
Devices with the error (only two examples, there are more):
Samsung SM-N910F (Webview: Chrome Mobile 53.0.2785, Android 6.0.1)
Samsung SM-G800F (Webview: Chrome Mobile 53.0.2785, Android 5.1.1)
If somebody's interested: The root cause was that people that upgraded Android somehow lost the chrome webview app and Angular was not working without one (of course). I solved it by packaging the crosswalk-webview in my app!

Categories

Resources