React native Xiaomi Phone axios not working - android

We developed an application with react native.
I will leave the link of the application below, I do not know if this is prohibited.
I pull data with axios, it works on all android devices. But it doesn't work on Xiaomi phones. I could not find the reason for this.
const api = "apiadress/deneme.php?lesid="+getLessonId;
axios.get(api).then((response)=>{
db.transaction((tx) => {
tx.executeSql('UPDATE lessons SET downloaded=? WHERE id=?', ['1',getLessonId]);
});
response.data.map((item) => {
db.transaction((tx) => {
tx.executeSql('INSERT INTO questions (questionname,lessonname,answerbame,aoptionname,boptionname,coptionname,doptionname,eoptionname,lessonid,oldidq) VALUES (?,?,?,?,?,?,?,?,?,?)',
[item.QuestionName,item.LessonName,item.AnswerName,item.AOption,item.BOption,item.COption,item.DOption,item.EOption,item.id,item.Id]);
});
});
console.log("Tüm sorular başarıyla kayıt edildi.");
});
An image of the code
link

I'm not sure what is the problem, but I had the a similar problem with axios (server requests didn't work after deployment)
You should consider leave axios and try using fetch:
POST:
fetch('http://mywebsite.com/endpoint/', {
method: "POST",
headers: {
// Authorization: "Bearer " + Token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
// sending data userID username, password, etc
}),
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});
GET:
fetch('http://mywebsite.com/endpoint/', {
method: "GET",
headers: {
// Authorization: "Bearer " + Token,
// OR USER name PASSworrd
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});

Related

React Native android FormData response goes to catch block after .json()

I'm trying to POST data with FormData to get a response, on iOS it works as expected, but on android, it always goes to the catch block, I found out the reason for that is response.json() with error: [SyntaxError: JSON Parse error: Unrecognized token '']
Here is my code:
const onAndroidSucks = () => {
setLoading(true);
let formData = new FormData();
formData.append("number", number.replace(/\s+/g, '').substring(4));
formData.append("id", userID);
formData.append("token", userToken);
fetch(ENDPOINT, {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data'
},
body: formData
}).then(response => response.json()).then(response => {
if (response.res === 'no') {
Alert.alert('ჰეჰე');
} else {
setData(response);
}
setLoading(false);
}).catch(err => { Alert.alert(err.message); setLoading(false); } );
};
I don't understand what the actual problem is here.
It turned out that problem was okHttp on android. Looks like okHttp appends an empty string " " without a known reason.
Here is how I solved that issue with the workaround:
}).then(response => response.text())
.then((res) => JSON.parse(res.trim())).then(response => {

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

https connection in Android react-native not working on physical device after build

I created a simple app with react-native, using expo & Axios (for server requests)
Before build, while developing, all https requests worked fine.
After build, when running the apk on a physical device, https is not working at all.
The error I get with Logcat is "Network Error".
Other Internet connections (after build) in the app do work, like webview opening a web page or Firebase connections also.
analyzerApi.post('/analyze', urls) .then((res) => {
dispatch({type: 'get_result', payload: res.data.analysis})}).catch(err => console.log("Error in getting analyze.. " ,err.name, err.message))
(analyzerApi is an axios instance with baseUrl directed to my server)
This call will work for both HTTP and HTTPS Try this example for POST CALL
fetch('http://mywebsite.com/endpoint/', {
method: "POST",
headers: {
// Authorization: "Bearer " + Token,
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
// sending data userID username, password, etc
}),
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});
Try this example for GET CALL
fetch('http://mywebsite.com/endpoint/', {
method: "GET",
headers: {
// Authorization: "Bearer " + Token,
// OR USER name PASSworrd
Accept: 'application/json',
'Content-Type': 'application/json'
},
})
.then((response) => response.json())
.then((responseJson) => {
// Response will here
})
.catch((error) => {
alert(error);
});

Fetch request iin react native getting null parameters data from server in react native

I am trying to call from fetch request but I am passing parameters on request is fine but when I checked server-side getting null data I am unable to understand whats exact problem after I research i found that charset=utf-8 need to mention so I did still having the same issue.
const request = {
videoId: data.videoId,
comments: data.comments,
views: parseInt(data.views) + 1,
likes: data.likes,
shares: data.shares
}
alert(JSON.stringify(request));
fetch(URL + '/VideosController/updateVideo', {
method: 'POST', // or 'PUT'
headers: {
'Accept': 'application/json',
'content-Type': "application/json; charset=utf-8" // "text/html; charset=UTF-8",
},
body: JSON.stringify(request),
})
.then(response => response.json())
.then((postsJson) => {
alert('res1 + ' + JSON.stringify(postsJson));
})
.catch((error) => {
alert('Error:', JSON.stringify(error));
});

React Native Fetch API - can't access json or body of response [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
Trying to call an API to my backend with Fetch, but I can't access the response body. There's a loot of different notation and syntax about this on the internet and I can't figure out how to do it properly.
I've tried response.json() and responseJson, and stringyfying both. I don't get what I want which is the actual body of the response. It's meant to have a key/token that I then save.
responseJson returns this: responseJson:
{"_40":0,"_65":0,"_55":null,"_72":null}
This is my function:
export function LogIn(em, pass) {
return (dispatch) => {
console.log('LogIn called');
dispatch(logInIsLoading(true));
//from phone
*fetch('http://192.168.1.18:8080/rest-auth/login/', {
method: 'POST',
headers: {
// 'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'email': em,
'password': pass,
})
}).then((response) => {
console.log("response " + JSON.stringify(response));
if (!response.ok) {
console.log("ERROR: " + response.statusText);
throw Error(response.statusText);
}
dispatch(logInIsLoading(false));
return response;
})
.then((response) => {
responseJson = response.json();
console.log("responseJson: " + JSON.stringify(response.json()));
return responseJson
})
.then((responseJson) => {
AsyncStorage.multiSet([['key', responseJson.key], ['loggedIn', true]], () => {
console.log(responseJson.key);
dispatch(isLoggedIn(true));
dispatch(getKey(responseJson.key));
});
})*
.catch(() => dispatch(logInHasErrored(true)));
};
}
This is the response, but I can't get to the key in the body:
response {"type":"default","status":200,"ok":true,"headers":{"map":
{"allow":["POST, OPTIONS"],"set-cookie":
["csrftoken=DOMxD5IhNz5Vwm9a3niAR1tRyqBfNzUqnQMAEgk7AGwtwCgnRnZo9x0AMTM2IfK
q; expires=Fri, 22-Feb-2019 17:31:58 GMT; Max-Age=31449600; Path=/,
sessionid=er3fujv8ji96t41n1n8dlzb3zz1itwuj; expires=Fri, 09-Mar-2018
17:31:58 GMT; httponly; Max-Age=1209600; Path=/"],"content-type":
["application/json"],"content-length":["50"],"x-frame-options":
["SAMEORIGIN"],"vary":["Accept, Cookie"],"server":["WSGIServer/0.1
Python/2.7.14"],"date":["Fri, 23 Feb 2018 17:31:58
GMT"]}},"url":"http://192.168.1.18:8080/rest-auth/login/","_bodyInit":"
{\"key\":\"a9951fd6abff4fed35d9a8d1c275bf1212887513\"}","_bodyText":"
{\"key\":\"a9951fd6abff4fed35d9a8d1c275bf1212887513\"}"}
response.json() return Promise
AsyncStorage.multiSet - return Promise. Second parameter of multiSet is Function that will be called with an array of any key-specific errors found
export function LogIn(em, pass) {
return (dispatch) => {
console.log('LogIn called');
dispatch(logInIsLoading(true));
fetch('http://192.168.1.18:8080/rest-auth/login/', {
method: 'POST',
headers: {
// 'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
'email': em,
'password': pass,
})
}).then((response) => {
if (!response.ok) {
console.log("ERROR: " + response.statusText);
throw Error(response.statusText);
}
dispatch(logInIsLoading(false));
return response;
})
.then((response) => {
return response.json()
})
.then((responseJson) => {
console.log('responseJson', responseJson);
return AsyncStorage.multiSet([['key', responseJson.key],['loggedIn', true]], () => {
dispatch(logInHasErrored(true));
})
.then(() => {
dispatch(isLoggedIn(true));
dispatch(getKey(responseJson.key));
})
})
.catch(() => dispatch(logInHasErrored(true)));
};
}
This is pretty straight forward with axios.
First install axios by doing npm install --save axios
Then inside your Component do this:
handleInput = async() => {
const res = await axios.post('http://192.168.1.18:8080/rest-auth/login/', {
email: this.state.email,
password: this.state.password
});
const data = await res.json();
console.log(data);
}
Make sure you've stored email and password in this.state.email and this.state.password respectively and call handleInput when user presses the Submit button.
Don't forget to import axios import axios from 'axios'

Categories

Resources