0

hi I have a probleme there. I am coding a crud rest api with (mongo atlas,reactjs,nodejs,express) and want to perform some update data but when using axios.put it is not working. Also when I use postman with the backend (router.patch ..) it works the problem is I can't get axios.put in frontend working. Here is the axios.put syntax in front end:

handleUpdate = async(e) => {
    try{
       const res = await axios.put('http://127.0.0.1:3000/posts/'+e,{
           ville: this.state.ville
       })
       alert(res.data)
       console.log(res.data)
    }catch(err){
          console.log(err)
    }
}

and here is the backend part of code of router.patch: //Update a post {ville}

router.patch('/:PostId', async (req,res) => {
    try{
        const updatedPost = await Post.updateOne({_id : req.params.PostId}, 
            { $set: {ville: req.query.ville}
        });
        res.json(updatedPost);
    }catch(err){
        res.json({message: err});
    }
});

can U help please ??

2 Answers2

2

Hi thank you CyberEternal for your help and support, I have found the issue and the problem is solved. after changing both the backend and front end to put, I have released that in back end I need to write $set: {ville: req.body.ville} unstead of $set: {ville: req.query.ville} here is the new code in backend: //Update a post {ville}

router.put('/:PostId', async (req,res) => {
    try{
        const updatedPost = await Post.updateOne({_id : req.params.PostId}, 
            { $set: {ville: req.body.ville}
        });
        res.json(updatedPost);
    }catch(err){
        res.json({message: err});
    }
});

and here is the code in front end (I have also add a prompt so the user can enter the id in string format and added the id to the url):

handleUpdate = async(e) => {
    try{
        var person = prompt("Veuillez saisir l'Id de l'employé");
       const res = await axios.put('http://127.0.0.1:3000/posts/'+person,{
           ville: this.state.ville
       })
       alert(res.data)
       console.log(res.data)
    }catch(err){
          console.log(err)
    }
}

It Works !! Thanks !

0

You need to use the PUT method in the backend instead of the PATCH

router.put('/:PostId', async (req,res) => {
    try{
        const updatedPost = await Post.updateOne({_id : req.params.PostId}, 
            { $set: {ville: req.query.ville}
        });
        res.json(updatedPost);
    }catch(err){
        res.json({message: err});
    }
});

Or, use the PATCH method in the frontend side

const res = await axios.patch('http://127.0.0.1:3000/posts/'+e,{
           ville: this.state.ville
       })
CyberEternal
  • 2,259
  • 2
  • 12
  • 31