skip to Main Content

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


  1. Chosen as BEST ANSWER

    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.

    1. In my html I had action="" written twice.
    2. In my routes/survey when passing the variable i need to type ([data]).

  2. There are a several things wrong.

    First, the route on your server for your form is /survey (from action="/survey") in the <form> tag, but you only show a route for /.

    Second, action="POST" should be method="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.

    app.use(express.urlencoded());
    

    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).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search