Search code examples
node.jsjsonexpressejs

Issue with Redirecting After Deleting Blog Post in Node.js Express Application


I'm encountering an issue with redirecting users to the /blogs page after successfully deleting a blog post in my Node.js Express application. It just redirect them back to the /blogs/:id, which since its deleted throws them back an error.

This is the backend app.delete I used:

app.delete('/blogs/:id',(req,res)=>{
    const id = req.params.id;
    Blog.findByIdAndDelete(id)
    .then((result)=>{
        res.json({ redirect: '/blogs'})
    })
    .catch((error)=>{
        console.log(error)
    })
})

And this is the client side:

<script>
    const trashcan = document.querySelector('a.delete');
    trashcan.addEventListener('click',(event)=>{
        const endPoint = `/blogs/${trashcan.dataset.doc}`;

        fetch(endPoint,{
            method: 'DELETE'
        })
        .then((response)=>{response.json()})
        .then((data)=> console.log(data))
        .catch((error)=>{
            console.log(error);
        })
    })
</script>

I am not sure whats causing the issue since I am following a youtube vid, https://youtu.be/VVGgacjzc2Y?list=PL4cUxeGkcC9jsz4LDYc6kv3ymONOKxwBU&t=1262, But it doesnt seem to work as expected, I've tried to change the direction of the redirect, yet nothing... I would appreciate any feedback and if anyone knows how to get really good at MERNs I would appreciate it too! Thank you!


Solution

  • It seems like you are handling the backend well but the way that you handle the front end might be the issue In the front end you console the data instead of redirecting if the data exists so that might be the issue.

    trashcan.addEventListener('click', (event) => {
      const endPoint = `/blogs/${trashcan.dataset.doc}`;
    
      fetch(endPoint, {
          method: 'DELETE'
        })
        .then((response) => response.json())
        .then((data) => {
          console.log(data); 
        
          if (data.redirect) {
    
            window.location.href = data.redirect;
          } else {
            console.log("Error");
          }
        })
        .catch((error) => {
          console.log(error);
        })
    })