Home > Mobile >  How to get form data from EJS?
How to get form data from EJS?

Time:10-24

I'm new to this topic. I would like to learn more about EJS. The goal is to get my form the data after they click the submit button. The result in console.log that should be is the data I inserted in the form. This is working fine except that the data is NULL. This being the case I'm wondering. Below is my code. This is a snippet of code for my server.js page with controller

I am getting this EJS page by clicking on a button and doing AJAX, here is the code of onclick = getID(id of the element)

function getId(id)
{
  // console.log(id)

  var request3 = new XMLHttpRequest();


  request3.open('GET', `/update`);

  request3.setRequestHeader("Content-Type", "application/json");
  var body = {
    "id": id
  }
  request3.send();

  
  request3.addEventListener("load", function () {
  window.location.href = `localhost:8000/update/${id}`;

  })

}

End Point for /update/:userId

app.route("/update/:userId").get(
updatePageControllers)

Controller updatePageControllers

module.exports = async function(req, res)
{

    const userId = req.params.userId

    try{
       res.render("update", {id: userId });
    }
    catch(err)
    {
        // console.log(err)
        res.json(err);
    }

}

My ejs form page /update/:userId

    <h1>Updating Id <%= id %></h1>

<form method="post" action="/updateTime/<%= id %>" enctype="multipart/form-data">
    <input placeholder="name" name="name"/>
    <input placeholder="description" name="description"/>
    <input placeholder="price" name="price"/>
    <input placeholder="quantity" name="quantity"/>
    <input type="file" name="image" accept="image/*"/>
    <input type="submit" value="signup"/>
  </form>

End Point in which I am expecting the data

app.route("/updateTime/:userId")
.post((req,res)=>{
    console.log(req.body.name   "yeah")
    res.end();
})

CodePudding user response:

To process multipart/form-data request, you need to use a middleware for that, such as multer.

So, setup multer, and since you're uploading a file, it should look something like this:

// setup multer
const multer = require('multer');
const upload = multer({...}) // setup

app.route("/updateTime/:userId")
// call multer middleware to process multipart
.post(upload.single('image'), (req,res)=>{
    console.log(req.body.name   "yeah")
    res.end();
})
  • Related