1
I’m trying to send a Formdata() to the backend via Fetch API, but I can’t read the form inputs in NODEJS. By the way, req.body is empty.
I’m wearing the body-parser and express.
Backend:
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
app.use(express.static('./static/'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.post('/teste', (req,res) => {
console.log(req.body);
res.send('teste');
});
app.get('/', (req,res) => {
res.sendFile(__dirname + '/index.html');
});
app.listen(3000, () => {
console.log('rodando...');
});
module.exports = () => app;
Frontend:
window.onload = () => {
var form = document.getElementById('myForm');
form.addEventListener('submit', (evt) => {
evt.preventDefault();
var myHeader = new Headers();
// myHeader.append('Content-type', 'application/x-www-form-urlencoded');
// myHeader.append('Content-type', 'multipart/form-data');
var myFormData = new FormData(form);
fetch('/teste', {
method: 'POST',
headers: myHeader,
body: myFormData
}).then((retorno) => {
console.log(retorno);
}).catch();
});
}
I can read something in req.body only when Content-type is equal to 'application/x-www-form-urlencoded'. In this case this is what appears on the console.log():
{
'------WebKitFormBoundaryUlQT9OMwOZvpVQ0U\r\nContent-Disposition: form-data; name': '"nome"\r\n' +
'\r\n' +
'digitando algo \r\n' +
'------WebKitFormBoundaryUlQT9OMwOZvpVQ0U\r\n' +
'Content-Disposition: form-data; name="idade"\r\n' +
'\r\n' +
'ABACATE\r\n' +
'------WebKitFormBoundaryUlQT9OMwOZvpVQ0U--\r\n'
}
man, thank you so much!
– Diego Armando Cacilha