API fetching in ReactNative - android

my name is Leo, I'm a newbie in Reactnative
I'm trying to make a login to my app and i met a problem with fetch API.
i recieved [TypeError: Network request failed]. I run on device API 30
here is my code:
const loginHadle = async(email, password)=>{
await fetch ('http://127.0.0.1:8000/login/',{
method:'POST',
headers:{
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({"email": email, "password":password})
}).then(response=>{
if(response.status==200)
{
response.json().then(data=>{
signIn(data.email, data.tokens);
})
}
})
.then(res => {
console.log("reponse :", res);
}).catch(error => {
console.error(error);
return { name: "network error", description: "" };
});
}
and I've already add this line to AndroidManifest.xml
android:usesCleartextTraffic="true"
here is what i receive on postman
Thank you very much!

On Android 9 because of the "http" and issue resolved by just adding android:usesCleartextTraffic="true" in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application android:usesCleartextTraffic="true"> . . . </application>

Related

React native image picker camera crashes

I am using image picker in react native but an error occurs:
file:///storage/emulated exposed beyond app through clipdata.item
On ios, the camera opens normally. and in android i can pick an image from gallery normally.
My code:
const selectFile = (itemI,inputValue) => {
let options = {
title: 'Select Image',
maxWidth:800,
maxHeight:800,
quality:0.2,
storageOptions: {
skipBackup: true,
path: 'images',
},
includeBase64: true,
saveToPhotos:true
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log(
'User tapped custom button: ',
response.customButton
);
alert(response.customButton);
} else {
//let source = response;
// You can also display the image using data:
let source = {
uri: 'data:image/jpeg;base64,' + response.data
};
filePath[itemI]=source;
addItemCustom(" ");
}
});
};
I tried to add:
<uses-feature android:name="android.hardware.camera.any" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
....
android:requestLegacyExternalStorage="true"
...>
but the error is the same.

React Native 0.66.* axios call [TypeError: Network request failed] ANDROID

Hi i am new in react native
i have macbook and i am running Laravel projects in macbook by using Laravel valet park
simple i am trying to generating Auth token by using any API which is developed in laravel 8. when i hit API by using postman then i got 100% response. but when i try to hit this API by using axios in react native always i am getting "NETWROK ERROR" in response.
import axios from 'axios';
axios.defaults.baseURL = 'http://cms.test/';
const LoginScreen = ({navigation}) => {
const [email,setEmail] = useState('');
const [password,setPassword] = useState('');
const [user, setUser] = useState(null);
const [error, setError] = useState(null);
const login = async() => {
if(!email || !password){
Alert.alert('Please fill all fields')
}else{
axios.post('api/token', {
email,
password,
device_name: 'mobile',
}, {
headers: {
'Content-Type': 'application/json'
}
})
.then(response => {
const userResponse = {
email: response.data.user.email,
token: response.data.token,
}
setUser(userResponse);
setError(null);
// SecureStore.setItemAsync('user', JSON.stringify(userResponse));
AsyncStorage.setItem('user', JSON.stringify(userResponse));
})
.catch(error => {
console.log(error);
return false;
const key = Object.keys(error.response.data.errors)[0];
setError(error.response.data.errors[key][0]);
})
}
}
Always getting "NETWORK ERROR" in response.
Note: i already updated AndroidManifest.xml file by these below linse
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<application android:usesCleartextTraffic="true" tools:targetApi="28" tools:ignore="GoogleAppIndexingWarning" />
But there is not any change, still getting "NETWORK ERROR", on hit API
Some times android emulator get problem with network when your wifi network changed or reconnected re-run your emulator again.

FileSystemException: Creation failed, path = '/storage/emulated/0/4k' (OS Error: Permission denied, errno = 13) Flutter

I have added every thing required to download files to local storage still I'm getting this error
In Manifest
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_MEDIA_LOCATION"/>
android:requestLegacyExternalStorage="true"
android:hardwareAccelerated="true"
In pubspec.yaml
permission_handler: ^6.1.1
In Build.gradle
compileSdkVersion 30
minSdkVersion 22
targetSdkVersion 30
Future<bool> _requestPermission(Permission permission, Permission permission3,
Permission permission4) async {
print("xxxx IN ");
if (await permission.isGranted) {
print('xxxx ohhh');
return true;
} else {
await permission.request();
.then((value) => () {
print("xxxx value" + value.toString());
if (value == PermissionStatus.granted) {
print("xxxx PERMISSION GRANTED ");
return true;
} else {
print("xxxx PERMISSION DENIED ");
}
})
.whenComplete(() => print('xxxx COMPLETED'))
.onError((error, stackTrace) => () {
print("xxxx onError " + error);
print("xxxx onError " + stackTrace.toString());
})
.catchError((onError) => () {
print('xxxx catchError ' + onError.toString());
});
print("xxxx OUT ");
// var result2 = await permission3.request();
// var result3 = await permission4.request();
}
return false;
}
from this function see what's printed
not getting printed from then()...
Please Please help me out :)
Use android:requestLegacyExternalStorage="true" in the application tag not in <activity> tag:
<application
android:requestLegacyExternalStorage="true" >
what is work for me this
permission_handler: ^8.3.0 // use this version
and in your code
final status = await Permission.storage.request();
var state = await Permission.manageExternalStorage.status;
var state2 = await Permission.storage.status;
if (status.isGranted) {
directory = (await getExternalStorageDirectory())!;
}
if (!state2.isGranted) {
await Permission.storage.request();
}
if (!state.isGranted) {
await Permission.manageExternalStorage.request();
}
if (!await directory!.exists()) {
await directory.create(recursive: true);
}
and in the my permissions
<uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-
permission>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission
android:name="android.permission.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION"/>

React Native Geolocation Timed Out

I use geolocation to get the current location of users in my project. but I get the Timed Out Error error.
{TIMEOUT: 3, POSITION_UNAVAILABLE: 2, PERMISSION_DENIED: 1, message: "Location request timed out", code: 3}
API 28 android phone success,
API 21 android phone success,
API 23 android phone time out error.
All permission granted.
try{
Geolocation.getCurrentPosition(
position => {
const initialPosition = JSON.stringify(position);
this.setState({
firstLat: position.coords.latitude,
firstLng: position.coords.longitude,
});
this.getLocation(position.coords.latitude, position.coords.longitude);
this.setState({
isLoading:true
})
},
error => console.log(error),
{enableHighAccuracy: true, timeout:10000, maximumAge:1000},
);
}catch (e) {
console.log(e)
}
AndroidManifest.xml
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
thank you.

Network Request Failed in react-native when trying to register using API

I am trying to build a registration page in react-native which sends the data to an API. Whenever I try filling the form and sending the request, the emulator throws a Network Request Failed error. I am using Android Emulator that comes with Android Studio. I have read almost all related answers but none of them seem to help me. I am working with Android 6.0 API level 23. The code and the error screenshots are attached below. And yes, I have enabled internet permission in manifest file.
handleSignup(event) {
Alert.alert("Sigup was pressed!");
fetch(' https://example.com/v1/users/register', {
method: 'post',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
password: this.state.password,
firstName: this.state.firstName,
lastName: this.state.lastName,
mobile: this.state.mobile
})
})
.then(response => {
// console.log('sss', response);
return response.json();
})
.catch((error) => {
console.error(error);
});
}

Categories

Resources