Express,Multer,BodyParser req.body空数组

时间:2016-09-06 17:12:45

标签: express multer body-parser

很抱歉这样一个noob问题,但我有一个表格上传图片并向DB添加一些文字,图片上传很好,但req.body对象总是一个空数组。

HTML

<form class='new-project' action='/projects' method='POST' enctype="multipart/form-data">
  <input type="text" name="title" placeholder="Project Title">
  <br>
  <textarea name="description" rows="8" cols="40" placeholder="Project description"></textarea>
  <br>
  <label for='file'>Select your image:</label>
  <input type='file' accept='image/*' name='uploadedImages' multiple/>
  <span class='hint'>Supported files: jpg, jpeg, png.</span>
  <br>
  <input type="submit" value="uploading_img">
</form>

JS

var bodyParser = require('body-parser'),
express    = require('express'),
multer     = require('multer'),

var storage = multer.diskStorage({
  destination: function (request, file, callback) {
    callback(null, './public/uploads');
  },
  filename: function (request, file, callback) {
    console.log(file);
    callback(null, file.originalname)
  }
});

var upload = multer({storage: storage}).any('uploadedImages');

app.use(bodyParser.urlencoded({extended:true}));
app.use(bodyParser.json());

app.post('/projects', function(req, res){
  console.log('req.body');
  console.log(req.body);
  upload(req, res, function(err){
    if(err){
      console.log('Oh dear...');
      console.log(err);
      return;
    }
    console.log(req.files);
    res.end('Your files uploaded!');
    console.log('Yep yep!');
  });
});

根据文档,multer为请求添加了一个body对象,但是我只返回一个带有或不带body-parser的空数组。

感谢您花时间浏览代码!!

1 个答案:

答案 0 :(得分:1)

您可以在upload()方法中获得所需req.body。 尝试在您打印req.body的位置记录req.files