Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.9k views
in Technique[技术] by (71.8m points)

javascript - Express body-parser req.body with formdata is empty object

Somehow my req.body is always empty, maybe you have an idea:

here is my server code:

const Express = require('express');
const bodyParser = require('body-parser');

const app = new Express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.post('/save', (req, res) => {
  console.log(req.body)  // => {}
  res.send(req.body);
});

const env = process.env.NODE_ENV || 'production';
app.listen(3000, err => {
   if (err) { return console.error(err); }
   console.info(`Server running on http://localhost:${port} [${env}]`);
});

When I try to send formdata with javascript the req.body is empty:

const data = new FormData(document.querySelector('form'));
console.log(data);  // seems empty already??? FormData{}??
const xhr = new XMLHttpRequest();
xhr.open('POST', 'http://localhost:3000/save');
xhr.send(data);

Same with postman:

postman

I don’t understand this…

Sending x-www-form-urlencoded with postman or raw (application/json) works in postman. But sending the same headers with Formdata in javascript will still result in an empty object…

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

To log every field in formData

let myForm = document.getElementById('myForm');
formData = new FormData(myForm);

for (let [key, value] of formData.entries()) { 
  console.log(key, value);
}

Fiddle - https://jsfiddle.net/thesumit67/j4znhxa5/1/

To handle it via express use multer. Here is an example - https://www.npmjs.com/package/multer

Make sure to add enctype="multipart/form-data" on form element. Otherwise Multer will ignore it.

let multer = require('multer');
let upload = multer();

app.post('/save', upload.fields([]), (req, res) => {
  console.log( req.body );
  console.log( req.files );
  res.sendStatus(200);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...