Express 4 Multer / req.body 和 res.json 未定义

Express 4 Multer / req.body and res.json not defined

我正在尝试使用 Express 4.0 和 multer 1.1.0 上传单个图像文件 + 文本字段。图片文件本身正确上传到正确的目的地,但我在文本字段和响应中遇到错误:

1) multer's req.body req.file objects are undefined if logged in console

2) res.json (and also res.send when tested) gets the error - TypeError: res.json is not a function at Object.handle)

multer 使用 moment.js 作为日期配置如下,这几乎是 multer Github 文档中的一行:

//standard express-generator server.js requires
//passport.js implementation

var multer   = require('multer');

var storage = multer.diskStorage({
  destination: function(req, file, cb){
    cb(null, './public/photoUploads/' + moment().year() + moment().month());
  },
  filename: function(req, file, cb){
    cb(null, req.user._id + moment().unix());
  }
})

var upload = multer({storage:storage});

require('./app/routes.js')(app, passport); //passport login routes - will eventually move app.post into this file

app.post('/upload/photoData', upload.array('photo'), function(err, req, res) {

   var title = req.body.title;
   var description = req.body.description;
   var photoURL = req.file.filename;

   var jsonResponse = {
     "title": title,
     "description": description,
     "photoURL": photoURL
   }

   console.log(jsonResponse);
   res.json(jsonResponse);
});

这是客户端表单

 <form id="photo-data" method="post" action="/upload/photoData" enctype="multipart/form-data">
        <div class="form-group">
            <div class="modal-body">

                <label for="image" class="control-label">Photo upload</label>
                <input type="file" class="form-control" name="photo" id="photo-main">

                <label for="caption" class="control-label">Title:</label>
                <input type="text" class="form-control" name="title" id="photo-title">

                <label for="long-text" class="control-label">Further description:</label>
                <input type="text" class="form-control" name="description" id="message-text">
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
                <button id="submit-photo" type="submit" class="btn btn-primary">Upload</button>                   
            </div>
      </div>
    </form>

我做错了什么?

Express 中错误处理程序的签名是 (err, req, res, next)(4 个参数),但 Express 在您的处理程序中看到的参数少于 4 个,因此它假设您正在添加一个普通的路由处理程序。问题是你的路由处理程序参数的顺序是错误的,它应该只是 (req, res)。这将修复您的 res.json() 错误。

对于您的文件字段,您目前告诉 multer 您需要多个文件,因此在这种情况下您将需要检查 req.files 而不是 req.file。如果您改用 upload.single('photo'),则可以使用 req.file.

对于非文件字段,请使用浏览器的开发人员工具检查表单提交的网络请求,确保它们确实已提交到服务器。