node.js 如何处理来自 express 4 的 FormData

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37630419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:17:04  来源:igfitidea点击:

How to handle FormData from express 4

node.jsexpressexpress-4

提问by SuperUberDuper

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

我尝试将一些表单数据发送到我的节点服务器,但req.body在节点端没有我的表单字段

 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 中传递的数据,也许这是我的问题

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

引用者:http://localhost:3000/?name=&budget=%C2%A31000

回答by robertklep

body-parserdoesn't handle multipart bodies, which is what FormDatais submitted as.

body-parser不处理多部分主体,这FormData是提交的内容。

Instead, use a module like multer.

相反,使用像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);
});