Home > OS >  What do I put in my form action when the router.post() has an :id
What do I put in my form action when the router.post() has an :id

Time:12-10

I am not sure how to submit data to my update form and what I have to put in the action field as the router.post has an :id. Below is my code:

router.post('/gymupdate/:id',async(req,res) => {

    
      let gymName = req.body.firstname;
      let location = req.body.city;
      let phoneNumber = req.body.mobile;
      let priceRange = req.body.price;
      let id = req.params.id;

      
     try{
      check2(gymName,location,phoneNumber,priceRange);
      if(!id) throw 'Pleaase provide an id';
      var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
      if(checkForHexRegExp.test(id)===false) throw 'Not a valid objectid';
      
    
      const updategym = await gymData.update(id,gymName,location,phoneNumber,priceRange)
      if(updategym)
        res.status(200).redirect('/gyms')
      else {
          res.status(500).render('gymbars/updategym', {title: "Error", error: 'Internal Server Error'})
      }
    }
    catch(e){
      res.status(400).render('gymbars/updategym', {title: "Error", error: e})
    }
  });

Form:

<form method="POST" action="/gyms/gymupdate/:id" id="signup-form" ></form>

The content in the action does not work, so how do I add id field to the action part similar to the router.post method?

This is how the user gets the id:

 router.get('/gymupdate/:id',async(req,res) => {
    
    
      const id = req.params.id;
    
      const values = await gymData.getGym(id);
      
    try{
      if (req.session.user && req.session.user.role === 'owner'){
        res.render('gymbars/updategym',{values:values})
      }
      else if(req.session.user && req.session.user!=='owner')
        res.redirect('/login')
      else{
        res.redirect('/login')
      }
    }
    catch(e){
      res.sendStatus(500);
      
    }
  });

So the logic goes like, I display a list of gyms as links, once you click on them you get to the gym profile. There is a button there that says update this gym, once clicked it goes to the update gym page which is being talked about here.

CodePudding user response:

if you are using any language for front end there is a way to write dynamic URL

but if you use pure HTML then this will help you

<form id="form_id" method="post" action="/aa">
    <input type="submit">
</form>
<script>
    document.getElementById("form_id").action = "/bbbbbb";
</script>

you need to bring your id

let id_to_pass//=get id which you want to pass in post api
document.getElementById("form_id").action = "/gymupdate/" id_to_pass;
  • Related