1

So in my React app I have a button that opens the camera and takes a picture , I want to send that picture to the backend. Below is my code

React js code

const DetectDisPage = () => {

  //State to render Camera when button is clicked
  const [cameraIsOpen , setCameraIsOpen] = useState(false);

  //State to maintain capture
  const [isCapture , setIsCapture] = useState(false);

  //Function to open camera
  const openCamera = () => {
    setCameraIsOpen(true)
  }

   //Function to close camera
   const closeCamera = () => {
    setCameraIsOpen(false)
  }

  //Confirming picture and if button is clicked should save image in database
  const confirmPicture =  () => {
    //THIS IS WHERE I WANT TO INSERT THE CODE TO SEND TO BACKEND
  }
  
  //Web Component
  const WebcamComponent = () => <Webcam />;

  const [imgSrc , setImgSrc] = useState(null)

  const webcamRef = useRef(null)

  const capture = useCallback(() => {
    const imageSrc = webcamRef.current.getScreenshot();
    setImgSrc(imageSrc);
    setIsCapture(true);
    setCameraIsOpen(false)

  }, [webcamRef, setImgSrc]);


  return (
    <>
      <Navbar />

      <div className={styles.mainCont}>
        <p>Take a picture of suspected Plant or Crop</p>

        {isCapture ? 
          <div className = {styles.cameraCont}> 
            <p onClick= {confirmPicture}>Confirm Picture</p>
          </div>
          :
          <div className= {styles.cameraCont}>
          {
            cameraIsOpen ? 
            <p onClick= {closeCamera}>Close Camera</p>
            :
            <p onClick= {openCamera}>Open Camera</p>
          }
          
        </div>
        }
        
{
  cameraIsOpen ? 
  <div className = {styles.webCamCont}> 
    <Webcam 
    audio={false} 
    ref={webcamRef} 
    screenshotFormat="image/jpeg" /> 
    
    <div className= {styles.captureButtonCont}>
      <button className= {styles.captureButton} onClick={capture}>Take picture</button> 
    </div>
    
    </div> 
    
    : null
}

    {imgSrc && (
        <img
          src={imgSrc}
        />
      )}


      </div>
    </>
  )
}

export default DetectDisPage

Here is my backend assuming I want to send it to the route and my backend is listening on port 4000

app.get('/saveImg' , (req ,res) => {

}

I want it so that when i click the "Confirm Picture" button it sends it to that route , I want to send the imgSrc to that backend route. What must I do because anything I put in the function for the Confirm Picture button is not working , must I useEffect anything? I am a beginner at React so any help is highly appreciated.

I also tried a simple console.log for the when the confirm button is clicked but it never showed up

2 Answers 2

1

here multiple solutions you can follow but for sending data back from frontend you have to use POST request for getting you have to use GET bit in both ways you can get response from server either a message or data so what you have to do is

const sendDatatoBackend = () => {
axios({
  method: "POST",
  url: "/api/url/thiscanbeanything",
  data: {
    image: image:path, //here you can add data as an object
  },
})
.then(res => {
  console.log("res", res.data.message);
})
.catch(err => {
  console.log("error in request", err);
});
}
// you can call this function on button click
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

Sign up to request clarification or add additional context in comments.

Comments

0

You should use fetch to send data from your react app to backend

const confirmPicture = async () => {
 const response = await fetch("http://localhost:4000/saveImg", {
  method: "POST",
  body: JSON.stringify({
    // here write your data to send
  }),
 });
 const data = await response.json();
 console.log(data); 
};

but you use in your api /saveImg GET method to send a data, you should modofied to POST method.

3 Comments

Got this error back - Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0 and when i make the backend a .post and i console.log(req.body) I get an empty object @hazem brayek
did you add your data in body object ?
yes in the part where you said i should put the data i put imgSrc (Which is the screenshot taken after Take Picture button is clicked

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.