无法读取未定义的属性 - Ajax POST

时间:2016-07-02 04:26:14

标签: javascript jquery ajax mongodb express

我试图从ajax发布数据(上传音乐文件),然后当我点击“上传”时,应该将数据保存到我的mongodb中。按钮。但是,我一直在获取fieldname是未定义的。我认为在我的代码中某处,它没有获取数据。

$('#upload').on('click', function(){ 
          var formData = new FormData($('#file')[0].files[0]);

            $.ajax({
              url: 'http://localhost:3000/api/',
              method: 'POST',
              // data: {
              //    file: $('#file')[0].files[0]
              //  },
              data: formData,
              contentType: false,
              processData: false,
              mimeType: "multipart/form-data",
              success: function(data){  //if successful upon grabbing data
                console.log(data);
                console.log('Created music')
                var id = $('<p>').text("Id:" + data[i]._id);
                var title = $('<p>').text("Title:" + data[i].originalname);
                var play = $('<button>').data('Data-id', data[i]._id).text('Play').on('click', playSong); //creates edit button with donut id and carries a function editDonut in which we will define later

                var del = $('<button>').data('Data-id', data[i]._id).text('Delete').on('click', deleteMusic);  
                var container = $('<div>').attr('Data-id', data[i]._id);
                $(container).append(id, title, play, del); 
                $('body').append(container) 
                // $('#new-form').hide();  
              }
          })
        })

的index.html

<form id="new-form">
  <input id="file" type="file" name="uploads">
  <button id="upload">Upload</button>
</form>

Express中的后端 - apiRouter.js

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './public/uploads/'); //UPLOAD MUSIC PATH
  },
  filename: function (req, file, cb) {
    var originalname = file.originalname;
    var extension = originalname.split(".");
    filename = Date.now() + '.' + extension[extension.length-1];
    cb(null, filename);
  }
});

router.post('/', multer({storage: storage}).single('uploads'), function(req,res){
  console.log(req.body);
  var music = new Music ({
    fieldname: req.file.fieldname,
    originalname: req.file.originalname,
    encoding: req.file.encoding,
    mimetype: req.file.mimetype,
    destination: req.file.destination,
    filename: req.file.filename,
    path: './uploads/' + req.file.filename,//req.file.path,  //PATH TO PLAY MUSIC
    size: req.file.size
  })
  music.save(function(err){
    if (err){console.log(err)}
    else {
      res.redirect('/');
    }
  })
});

在Express - app.js

app.use('/api', apiRouter);

终端错误

TypeError: Cannot read property 'fieldname' of undefined
    at /Users/will/pulse-express2-passport/config/apiRouter.js:72:24
    at Layer.handle [as handle_request] (/Users/will/pulse-express2-passport/node_modules/express/lib/router/layer.js:95:5)
    at next (/Users/will/pulse-express2-passport/node_modules/express/lib/router/route.js:131:13)
    at Array.<anonymous> (/Users/will/pulse-express2-passport/node_modules/multer/lib/make-middleware.js:52:37)
    at listener (/Users/will/pulse-express2-passport/node_modules/on-finished/index.js:169:15)
    at onFinish (/Users/will/pulse-express2-passport/node_modules/on-finished/index.js:100:5)
    at callback (/Users/will/pulse-express2-passport/node_modules/ee-first/index.js:55:10)
    at IncomingMessage.onevent (/Users/will/pulse-express2-passport/node_modules/ee-first/index.js:93:5)
    at emitNone (events.js:86:13)
    at IncomingMessage.emit (events.js:185:7)
    at endReadableNT (_stream_readable.js:934:12)
    at _combinedTickCallback (internal/process/next_tick.js:74:11)
    at process._tickCallback (internal/process/next_tick.js:98:9)

1 个答案:

答案 0 :(得分:3)

FormData构造函数需要一个表单,从中提取键(元素名称)和值。将表单而不是文件传递给构造函数。

var formData = new FormData($('#new-form')[0]);

或者您可以创建一个空的FormData对象,然后将值添加到它。

var formData = new FormData();
formData.append('uploads', $('#file')[0].files[0]);