I have implement an barcode scanner app by using react native when I use web to execute the program all the function are work perfectly it can pass the data to api and post to the server but when I try to use it on my android and iOS device it cannot post the data below is my code for scanner.js
import React, { useState, useEffect,Component,onMount} from 'react';
import { Text,TextInput, View, StyleSheet, Button } from 'react-native';
import { BarCodeScanner } from 'expo-barcode-scanner';
import {useNavigation} from'@react-navigation/native';
import {StatusBar} from 'expo-status-bar';
export default function Scanner () {
const [hasPermission, setHasPermission] = useState(null);
const [scanned, setScanned] = useState(false);
const [userid, setuserid] = useState('Not yet scanned')
const [currentDate, setCurrentDate] = useState('');
const navigation = useNavigation();
const askForCameraPermission = () => {
(async () => {
const { status } = await BarCodeScanner.requestPermissionsAsync();
setHasPermission(status === 'granted');
})()
}
// Request Camera Permission
useEffect(() => {
askForCameraPermission();
}, []);
useEffect(() => {
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var hours = new Date().getHours(); //Current Hours
var min = new Date().getMinutes(); //Current Minutes
var sec = new Date().getSeconds(); //Current Seconds
setCurrentDate(
date '/' month '/' year
' ' hours ':' min ':' sec
);
}, []);
// What happens when we scan the bar code
const handleBarCodeScanned = ({ type, data }) => {
setScanned(true);
setuserid(data )
};
// Check permissions and return the screens
if (hasPermission === null) {
return (
<View style={styles.container}>
<Text>Requesting for camera permission</Text>
</View>)
}
if (hasPermission === false) {
return (
<View style={styles.container}>
<Text style={{ margin: 10 }}>No access to camera</Text>
<Button title={'Allow Camera'} onPress={() => askForCameraPermission()} />
</View>)
}
const Register = () => {
let InsertAPIURL = "https://localhost/api/insert.php";
let headers = {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': 'POST, PUT, PATCH, GET, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Origin, X-Api-Key, X-Requested-With, Content-Type, Accept, Authorization',
}
let Data = {
userid:userid,
};
fetch(InsertAPIURL, {
mode:'no-cors',
method: 'POST',
headers: headers,
body: JSON.stringify(Data)
})
try{
((response) =>response.json()),
((response)=>{
alert(response[0].Message);
})
}
catch{
((error) => {
alert("Error" error);
})
} }
// Return the View
return (
<View style={styles.container}>
<View style={styles.barcodebox}>
<BarCodeScanner
onBarCodeScanned={scanned ? undefined : handleBarCodeScanned}
style={{ height: 400, width: 400 }} />
</View>
<Text style={styles.maintext}>{userid '\n' currentDate}
</Text>
{
scanned && <Button title={'Scan again?'} onPress={() => setScanned(false)} color='tomato' />
}
{
scanned && <Button title={'OK'} onPress={()=> navigation.navigate('Home',{userid},Register())} />
}
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
maintext: {
fontSize: 16,
margin: 20,
},
barcodebox: {
alignItems: 'center',
justifyContent: 'center',
height: 300,
width: 300,
overflow: 'hidden',
borderRadius: 30,
backgroundColor: 'tomato'
}
});
I have make a research on other source they said that change the apiurl to http://10.0.2.2 instead of localhost host to made it function on android device but after I tried this method it also cannot solve the issue. this is my first react native project and I really hang on this part a few day already hope u guys help thanks in advance
CodePudding user response:
You need to provide your ip address instead of the localhost
, you can find it by doing ifconfig
on linux/Mac and ipconfig
on windows.
So you have something like this: 192.0.0.1:3000/yoururl
instead of localhost:3000/yoururl
This is only needed if you want to test on a real device which is connected to your computer.