How to setup fetch for React Native Android using gzip? - android

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;
}
}

Related

why am i getting html response as data in GET Request of Restful api in android react native?

i am trying to fetch data using GET method for an Api.
it returns data in json in ios but in android it return html Script as shown in image,
let response = await axios.get('https://xxxxxxxx.com/api/reactappsettings/react_get_all_settings/?insecure=cool',
{headers:{
'Content-Type': 'application/json;charset=UTF-8',
'Accept' : 'application/json',
"Access-Control-Allow-Credentials": true,
},withCredentials:true})
console.log("======>",response);
i am stuck here due to this issue, any solutions?
i also tried using react-native-cookie to handle cookies .
CookieManager.get('https://mvhardhats.com')
.then(async (res) => {
console.log('CookieManager.get =>', res);
await axios.get(
`https://mvhardhats.com/api/reactappsettings/react_get_all_settings/?insecure=cool`,
{
headers: {
Cookie:`visid_incap_2485071=${res.visid_incap_2485071}; incap_ses_882_2485071=${res.incap_ses_305_2485071}`,
},
withCredentials:true
},
).then((data)=>{
console.log(data)
})
// => 'user_session=abcdefg; path=/;'
})
but still it returns html even after i got coockies.
Check the whitelist rule in your application and try this code:
Need to use .json() on the response.
let response = await axios.get('https://mvhardhats.com/api/reactappsettings/react_get_all_settings/?insecure=cool', {
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => response.json())
.then((response) => {
console.log("======>",response);
});

how to fix CORS issue for android version 9 at ionic 4

My Ioinc 4 is working at chrome and firefox browser, but cors does not wrok at android version 9. My Http Header is below.
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const token = localStorage.getItem('access_token');
this.loaderService.show();
if (token) {
request = request.clone({ setHeaders: {
'Authorization': token,
'Accept': 'application/json',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'*',
'Access-Control-Allow-Headers': '*',
}});
} else {
request = request.clone({ setHeaders: {
'Accept': 'application/json',
'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'*',
'Access-Control-Allow-Headers': '*',
}});
}
return next.handle(request).pipe(
map((event: HttpEvent<any>) => {
return event;
}),
catchError((error: HttpErrorResponse) => {
return throwError(error);
}),
finalize(() => {
this.loaderService.hide();
}));
}
You can use native http plugin for http request this handle cors automatically here is a link : https://ionicframework.com/docs/native/http

React native fetch() throws "Network request failed" on Android when response is long

fetch() has been working fine on both iOS and Android until a month ago. I found out that when the response is long it would throw Network request failed error:
Network request failed
onerror
whatwg-fetch.js:504:29
dispatchEvent
event-target.js:172:43
setReadyState
XMLHttpRequest.js:576:29
__didCompleteResponse
XMLHttpRequest.js:392:25
<unknown>
XMLHttpRequest.js:505:8
emit
EventEmitter.js:191:12
__callFunction
MessageQueue.js:344:47
<unknown>
MessageQueue.js:107:26
__guard
MessageQueue.js:291:8
callFunctionReturnFlushedQueue
MessageQueue.js:106:17
This is how I set up fetch requests:
const URLENCODED_HEADER = {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
}
async function getToken() {
try {
let response = await fetch(SERVER_URL+'/secure/token', {
credentials: 'include'
});
let responseJson = await response.json();
return responseJson.result
} catch(error) {
throw error;
}
}
async function doLogin(secureInfo) {
formBody = encodeParameters(secureInfo)
try {
let response = await fetch(SERVER_URL+'/user/login', {
method: "POST",
headers: URLENCODED_HEADER,
body: formBody,
credentials: 'include'
});
let responseJson = await response.json();
return responseJson;
} catch(error) {
console.error(error);
throw error;
}
}
Here are some responses that I was able to get back successfully:
1.
err_no: 0
result: BVV7IZVLOYgROXXc
2.
err_no:0
result:{
login_id:xxxx#gmail.com
user_name:""
email: xxx#gmail.com
user_id:11
login_type:1
}
However other longer responses, such as the one below, caused "Network request failed":
{
"err_no":0,
"result":[
{
"article_id":299,
"user_id":11,
"title":"society",
"content":"",
"text_content":"\n",
"tags":"[\"Society\"]",
"used_articles":"{}",
"citation_text":"",
"prompt":"",
"alternative_title":"",
"alternative_prompt":"",
"alternative_cnt":0,
"image_url":"",
"created":"2018-07-26 18:28:17",
"update_time":"2018-07-26 18:28:27"
}
]
}
(logged from web platform)
What could cause this and how should I fix it?

Including csrf token in a post request from react-native app

I have a react native app that posts and gets data from a remote server. In post, i need to include csrf token to avoid token mismatch errors. This is the backend laravel method
//Android Login
public function androidLogin(){
return response()->json([
'name' => 'Android Login',
'route' => 'androidLogin'
]);
}
This is the react native code(i have stripped out error catching code).
async handleSubmit(){
var me = this.state.message;
console.log('this connected',me);
let response = await fetch('http://not-brusselus.be/androidLogin', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'X-CSRF-TOKEN':'csrf_field()'
},
body: JSON.stringify({
session:{
email: 'chesterfield#gmail.com',
password: '123456',
}
})
});
//let res = await response.text();
if (true) {
console.log(response);
} else {
//Handle error
//let error = res;
//throw error;
}
}
The response shows laravel's token mismatch page. How can i send the csrf token successfully?.
Hang the CSRF token off of the window as defined in your main laravel layout file:
window.Laravel = {
csrfToken: '{{csrf_token()}}'
}
Then just use that in your javascript requests:
...window.Laravel.csrfToken
Edit
To the downvoter: This is literally how Laravel does it out of the box and recommends you do it as well.

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

Categories

Resources