0

I'm working with ReactJS as frontend and NodeJS as backend. If there is no url with such a parameter, I want to redirect but my codes are not working. Where am I missing?

<Router>
  <Routes>
    <Route path="/" element={<HomeScreen />} exact />
    <Route path="/create" element={<CreateScreen />} />
    <Route path="/update/:id" element={<UpdateScreen />} />
    <Route path="*" element={<Navigate to="/" />} />
  </Routes>
</Router>;

Backend:

router.get('/update/:id',async (req,res)=>{
    try {
        const {id} = req.params
        if(!mongoose.Types.ObjectId.isValid(id)){
            res.status(404).json({message:'not working'}).redirect('/') 
        }else{
            const memory = await Memory.findById(id)
            if(!memory) return
            res.status(200).json(memory)
        }
    } catch (error) {
        res.status(404).json({message:error.message})
    }
})
MarioG8
  • 5,122
  • 4
  • 13
  • 29
322quick1
  • 133
  • 1
  • 9
  • You're confusing the backend and frontend. The backend does not influence the frontend routing... – BENARD Patrick Dec 21 '21 at 17:34
  • where should I do the redirect? @BENARDPatrick – 322quick1 Dec 21 '21 at 17:35
  • Does this answer your question? [How to do a redirect to another route with react-router?](https://stackoverflow.com/questions/34735580/how-to-do-a-redirect-to-another-route-with-react-router) – IceJonas Dec 21 '21 at 17:37

1 Answers1

0

Your app is configured to perform URL Navigation on the front-end rather than via SSR on the backend. When the request is made on the front-end to express, the response object sent by express to the front-end should not include a redirect property. Try to focus on handling the redirect on the front-end.

For instance

let navigate = useNavigate();
if (res.statusCode === 404) navigate('/', {state: null, replace: true})

This is with react-router v6