How can we get radio button values from form using body-parser on an expressjs server?

Issue

I have a form and part of it asks the user if they are male or female. Here is the html,

<form role="form" id="createAccountForm" action="CAform" method="POST">
.
.
.
.
<div class="form-group" id="gender">
<label class="radio-inline"><input type="radio" name="optradio" value="1">Male</label>
<label class="radio-inline"><input type="radio" name="optradio" value="0">Female</label>
</div>
.
.
.
</form>

and on the server (a node server with express framework), I want to know how to access the gender value when the user submits the form. Can you do it with body-parser?

Solution

You just need to set the middlewares of bodyParser and you’re good to go.

var bodyParser = require('body-parser'); 
app.use(bodyParser.json()); // to support JSON bodies
app.use(bodyParser.urlencoded({ extended: true })); // to support URL-encoded bodies

app.post('/CAForm', function(req, res) {
  res.send(req.body.optradio);
});

Answered By – João Marcelo Brito

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published