Form with Node/EJS does not work!

Asked

Viewed 487 times

1

Good morning guys, I’m making a form, using Node and the EJS view engine, however I’m having trouble getting data from the forms in the controller. The return of req.body is always Undefined.

app.js with body-parser

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Form . EJS

<form method='post' action='/save' enctype='multipart/form-data'>
    <label> Paciente </label> <br />
    <input type='text' name='patient' value='oi' /> <br />

    <label> Imagem: </label> <br />
    <input type='file' id='image' name='image' /> <br />

    <label>Descrição: </label> <br />
    <textarea id='description' name='description' rows=3></textarea> <br />

    <button type='submit'> Enviar </button>
</form>

Controller, with post method:

router.post('/save', (req, res) => {
  console.log(req.body.patient);
  console.log(req.body.description);
});

1 answer

1

bodyParser can’t stand it multipart/form-data, an alternative may be to use the ladies. Example:

var express = require('express')
var multer  = require('multer')
var upload = multer({ dest: 'uploads/' }) // dest = destino onde ficara o arquivo

var app = express()

app.post('/save', upload.single('image'), function (req, res, next) {
  // req.file é o aquivo `image`
  // req.body terá os campos textos, se tiver algum 
})

Browser other questions tagged

You are not signed in. Login or sign up in order to post.