1

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

d.chan
  • 136
  • 9
  • You can't use localhost because localhost vary between clients. localhost of your emulator or device means localhost of that device. However if you are in the same network with your server, you can give the local network ip of your server. https://stackoverflow.com/a/53689093/5793132 – Ugur Eren Jun 21 '22 at 08:06
  • is it also need to make some change on xampp server? – d.chan Jun 21 '22 at 08:41
  • No, you don't need to change your server – Ugur Eren Jun 21 '22 at 14:02

1 Answers1

0

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.

lmasneri
  • 589
  • 7
  • 17
  • after i doing this it shown error when i inspect in network **Referrer Policy: strict-origin-when-cross-origin** – d.chan Jun 22 '22 at 00:25
  • i can find 2 ipv4 one is under **Wireless LAN adapter Local Area Connection* 2** and the other one is under **Wireless LAN adapter Wi-Fi** which one should i refers to? – d.chan Jun 22 '22 at 00:51
  • for the cross-origin I guess you will find how to solve and for the ipv4 it should be ipv6 but if you can try both of them – lmasneri Jun 22 '22 at 07:46
  • Happy that it helps you! you can upvote so that if someone else have the same issue he founds the answer faster! @d.chan – lmasneri Jun 22 '22 at 09:39