Form with Node / EJS does not work!

1

Good morning, I'm doing 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 the req.body is always undefined.

app.js with body-parser

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

.EJS Form

<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 method post:

router.post('/save', (req, res) => {
  console.log(req.body.patient);
  console.log(req.body.description);
});
    
asked by anonymous 05.01.2018 / 14:23

1 answer

1

bodyParser does not support multipart/form-data , an alternative might be to use multer . 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 
})
    
05.01.2018 / 14:48