Home > other >  Why is my redirect to my frontend not working (Express and React)
Why is my redirect to my frontend not working (Express and React)

Time:06-19

I have a react frontend that sends data to backend and then in the backend I save the data, however when i redirect to another page after saving to database it does not go, however , the data is actually saved in the database. Below is the code

index.js (Backend)

app.post('/saveImg' , async (req , res) => {
  const {image} = req.body

  const cropData = new CropInfo({
    image: image
  })

  //Save the entry
  await cropData.save()

  res.redirect('http://localhost:3000/login')
})

This is how the frontend is sending the data

const confirmPicture =   () => {
    //THIS IS WHERE I WANT TO INSERT THE CODE TO SEND Image TO BACKEND
     axios({
      method: "POST",
      url: "http://localhost:4000/saveImg",
      data: {
        image: imgSrc
      }
    })
    .then(res => {
      console.log("res", res.data.message);
    })
    .catch(err => {
      console.log("error in request", err);
    })

    
  }

I have a react route http://localhost:3000/login which loads a login page however for some reason the redirect in the backend is not working. Any advice on how to make it work? Am i doing anything wrong?

CodePudding user response:

Send the response back to frontend like res.json({message: "ok"}) and in react do programatically redirect based on the response back.

  import { useNavigate } from "react-router-dom";
  
  const navigate = useNavigate()

  fetch(URL,{OPTIONS})
   .then(res => res.json())
   .then(
    (result) => {
      if(result.message === "ok") {
      navigate("/login"); 
      }
    })

If you are using axios:

 axios.post(URL, {...})
  .then(function (response) {
    if(response.message === "ok") {
     navigate("/login")
    }
  })


  
  • Related