So I'm building a cat rescue website and when I add a new cat, I wanna be able to add its sex through a radio button (meaning , if the "Male" radio is selected, it should return true, or if the "Female" is selected, should return false), does anyone have any idea on how to do this?
These are the two radio buttons in html
<input class="form-check-input" type="radio" name="cat[sex]" id="radioMale" value="true">
<input class="form-check-input" type="radio" name="cat[sex]" id="radioFemale" value="false">
This is the POST route in my javascript file
app.post('/cats', async (req, res) => {
const cat = new Cat(req.body.cat);
await cat.save();
res.redirect(`/cats/${cat._id}`);
})
So I tried hard-coding the value to the inputs but it doesn't work. I have no idea how to solve this
req.body is not automatically populated with posted data. The 5.x Express documentation provides the following example which requires the installing and using NPN packages
body-parser andmulterExample:
const app = require('express')()
const bodyParser = require('body-parser')
const multer = require('multer') // v1.0.5
const upload = multer() // for parsing multipart/form-data
app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded
app.post('/profile', upload.array(), function (req, res, next) {
console.log(req.body)
res.json(req.body)
})
This differs from the examples shown in 4.x documentation which seems simpler and is something else you could try. If you want to research how to decode form data in Express, you will no doubt find further variations and not-to-mention multiple similar questions on this site.