Node.js 344错误发送后无法设置标题

试图把我的头绕过这个错误,我不明白为什么。 我看到了几个post,但他们都是不同的情况,没有一个适合我的。 所以感谢帮助。 我想上传多个file upload。 但我做file upload这只是一个工作。 但是当我尝试上传多个文件,这是行不通的,你能给我一个答案?

router.post('/contents/insert/upload', ensureAuthenticated, function(req, res, next) { var form = new formidable.IncomingForm(); form.parse(req); // form.on("fileBegin", function (name, file){ // console.log('upload come on3'); // // }); form.on("file", function (name, file){ fs.readFile(file.path, function(error, data){ var filePath = __dirname + '/../public/uploads/' + file.name; fs.writeFile(filePath, data, function(error){ if(error){ throw err; //res.redirect('back'); }else { res.redirect('back'); } }); }); }); }); 
 <form action="/adm/contents/insert/upload" method="post" enctype="multipart/form-data" > <!-- <input type="file" name="file" /> <input type="submit" /> --> <div class="file-field input-field"> <div class="btn"> <span>input images</span> <input type="file" name="file" multiple> </div> <div class="file-path-wrapper"> <input class="file-path validate" type="text"> </div> </div> <input type="submit" class="btn waves-effect waves-light" value="upload" /> </form> 

上传中的每个文件都会触发file事件,因此最终您的代码将为每个上传的文件发出res.redirect() 。 这将导致错误(您只能发出redirect,或发送一个响应,只有一次在请求的生命周期)。

相反,你想听end事件,并发出redirect在那里:

 form.on("file", function (name, file) { ...handle the file copy here, but don't call `res.redirect()` anywhere... }); form.on("end", function() { res.redirect('back'); }); 

FWIW,在我看来,你想要设置Formidable的uploadDir选项,或者使用fs.rename() ,而不是在上传后读取文件并将其写入新的位置(效率不高)。