I’m attempting to setup my html so that when the user submits the form i created it will be handled by the post route handler in order to save the data into the mondo DB.
I tried setting up my post route handler to take req.body.service but i believe that the html isnt passing any data because i used a console.log() once it arrives to the post route handler and nothing is written.
// survey.ejs
<h2>Feedback Survey</h2>
<div>
Please select the service provider you signed up for:<br>
</div>
<form action="/survey" action="POST" id="service">
<select name="service" id="service" required>
<option value="" disabled selected hidden>Type to search </option>
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
</select>
<br>
<button type="submit">Submit</button>
</form>
<a href="/index">Go back home</a>
</body>
</html>
// routes/survey.js
const express = require('express')
const router = express.Router()
const Survey = require('../models/survey')
router.post('/', async(req, res) => {
console.log('Before try catch statement')
try{
const data={
service: req.body.service
}
await Survey.insertMany[(data)]
res.render('index')
}catch (e){
console.log(e)
}
})
module.exports = router
// models/survey
const mongoose = require ('mongoose')
const surveySchema = new mongoose.Schema({
service: {
type: String,
required: true
}
})
module.exports = mongoose.model('Survey', surveySchema)
// middleware
app.use(express.urlencoded({ extended: false}))
2
Answers
So after looking over my code i was able to figure out the two issues that i had that was stopping me from passing the data from the submission form.
action=""
written twice.There are a several things wrong.
First, the route on your server for your form is
/survey
(fromaction="/survey"
) in the<form>
tag, but you only show a route for/
.Second,
action="POST"
should bemethod="POST"
in your<form>
tag.Third, your data will arrive as a content-type of
application/x-www-form-urlencoded
and you will need middleware on your express server to read that content-type.And, that middleware needs to be either on the specific route for the form or registered before that route.
This also assumes that you are registering the router you show with your Express server too (the code you’ve disclosed does not currently show that).