58

I tried sending some form data to my node server but req.body has none of my form fields the node side

 var express = require('express')
var app = express()
var path = require('path')
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({
  extended: true
}));

app.get('/', function (req, res) {
  res.sendFile('index.html')
})
app.post('/sendmail', function (req, res) {

  const formData = req.body.formData

this is what I'm sending from the browser

fetch('/send', {
  method: 'POST',
  body: new FormData(form)
})

in dev tools I only see the data passed in the Referer, maybe that is my issue

Referer:http://localhost:3000/?name=&budget=%C2%A31000

SuperUberDuper
  • 8,805
  • 9
  • 36
  • 71
  • `body-parser` doesn't handle multipart request bodies, try something like [`multer`](https://www.npmjs.com/package/multer). – robertklep Jun 04 '16 at 13:46
  • @robertklep I see thanks, feel free to add it to answer. Maybe it would be more simple if I just extra the data to JSON? I'm suprised that I can just pass FormData to fetch and its send as multipart. – SuperUberDuper Jun 04 '16 at 14:51

1 Answers1

124

body-parser doesn't handle multipart bodies, which is what FormData is submitted as.

Instead, use a module like multer.

For example, to retrieve the (regular) fields of a request:

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

app.post('/send', upload.none(), (req, res) => {
  const formData = req.body;
  console.log('form data', formData);
  res.sendStatus(200);
});
Masih Jahangiri
  • 6,571
  • 2
  • 35
  • 36
robertklep
  • 185,685
  • 31
  • 370
  • 359
  • 1
    thx, know of any utils to take form data and return it as a JSON object (for things like text inputs and the like) for sending via urlencoded – SuperUberDuper Jun 06 '16 at 11:43
  • 1
    @SuperUberDuper you probably have to use something like [`formData.entries()`](https://developer.mozilla.org/en-US/docs/Web/API/FormData/entries) to build a JS object from the form contents. – robertklep Jun 06 '16 at 11:56
  • What does happen behind the scene here `upload.fields([])` ? – Ced Jun 25 '17 at 19:25
  • 6
    If you can't get this to work, try `upload.any()` instead of `upload.fields([])`. You'll probably eventually want to figure out what field specifications you want to put in the array but `any` is a good place to start. – Ryan H. Jul 18 '17 at 20:11
  • is there no way to inject it like bodyparser? (`app.use(multer())` or similar) – phil294 Nov 24 '18 at 17:19
  • @Blauhirn might be difficult with `multer`, but [`express-fileupload`](https://github.com/richardgirges/express-fileupload) can be used like that. – robertklep Nov 24 '18 at 20:47
  • @Blauhirn lots of options :D – robertklep Nov 24 '18 at 20:51
  • 3
    after spending my whole day looking through 100s of a solution, and nothing work, then he finally saves my day, thank you soo much. – Nawaraj Sep 01 '19 at 01:13