Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

node.js - How to handle FormData from express 4

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

Question&Answers:os

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

1 Answer

0 votes
by (71.8m points)

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);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...