javascript – 错误:解析器错误,解析了4344字节的0(Node.js)

我正在尝试使用上传程序上传我的文件.我使用的代码是

app.post('/photos',loadUser, function(req, res) {
  var post = new Post();
  req.form.complete(function(err, fields, files) {
    if(err) {
      console.log(err);
      next(err);
    } else {
      ins = fs.createReadStream(files.file.path);
      ous = fs.createWriteStream(__dirname + '/public/uploads/photos/' + files.file.filename);
      post.filename=files.file.filename;
      post.file=files.file.path;
      util.pump(ins, ous, function(err) {
        if(err) {
          next(err);
        } else {
          post.save(function(err,docs) { 
        req.flash('info', 'information  Saved');
            res.redirect('/photos');
          });
        }
      });
    }
  });
});

当我删除loadUser方法时,一切正常,但是当我使用loadUser方法时,它给了我一个错误.错误的控制台信息是:

Error: parser error, 0 of 4344 bytes parsed
at IncomingForm.write (/home/darhamid/node_modules/formidable/lib/incoming_form.js:141:17)
at IncomingMessage.<anonymous> (/home/darhamid/node_modules/formidable/lib/incoming_form.js:91:12)
at IncomingMessage.emit (events.js:67:17)
at HTTPParser.onBody (http.js:121:23)
at Socket.ondata (http.js:1349:22)
at TCP.onread (net_uv.js:312:27)

该错误仅在我使用loadUser函数时引起,如果我删除loadUser Funciton一切正常.
我不知道背后的原因而且卡住了.有人可以帮我吗?

解决方法:

您正试图在所有事情之前执行数据库操作,这会给您带来问题.请尝试以下代码:

app.post('/potos', function(req, res, next) {
  //req.form.pause();
  req.form.complete(function(err, fields, files) {
    if(err) {
      next(err);
    } else {
      ins = fs.createReadStream(files.file.path);
      ous = fs.createWriteStream(__dirname + '/public/uploads/photos/' + files.file.filename);
      var post = new Post();
      post.filename=files.file.filename;
      post.file=files.file.path;
      post.created_at = new Date();
      post.user_id = req.session.user_id;

      function postCreationFailed() {
        req.flash('error', 'Unable to Download ');
        res.render('photos/new', {
          locals: {
             post: new Post(),currentUser: req.session.user_id
          }
        });
      }

      util.pump(ins, ous, function(err) {
        if(err) {
          next(err);
        } else { 
                 console.log('\nuploaded %s to %s',  files.file.filename, files.file.path);
                 post.save(function(err) {
                   if (err)
                return postCreationFailed();
                   req.flash('info', 'photos Succesfully Uploaded');
               res.redirect('/user/photos/'+post.user_id);
                });
              }
      });
    }
  });
  req.form.on('progress', function(bytesReceived, bytesExpected){
    var percent = (bytesReceived / bytesExpected * 100) | 0;
    process.stdout.write('Uploading: %' + percent + '\r');
  });

});

祝好运…

上一篇:javascript – 创建后挂钩


下一篇:javascript – Mongoose:如何替换子文档数组?