从nodejs后端发送callback到前端

我有一个fileUpload(用NodeJS制作),我想在{{upload.message}}中的html中显示上传的成功。 我用AngularJS实现了它,但是没有奏效。 我究竟做错了什么?

HTML

<form enctype="multipart/form-data" action="/upload" method="POST"> <div class="form-group"> <input type="file" name="file" /> <p></p> <input type="file" name="file" /> <p></p> <input type="file" name="file" /> <br> <br> <input type="submit" value="Upload File" name="submit" class="btn btn-primary"> </form> <span>{{upload.message}}</span> </div> 

的NodeJS

 router.post('/upload', function(req,res){ upload(req,res,function(err) { var fileNames = []; req.files.forEach(function(element){ fileNames.push(element.filename); }) console.log('Selected Files: ', fileNames); if(err){ res.end("Error: '" , err , "'"); }else{ res.sendStatus(204); } }); }); 

AngularJS

  var self = this; this.message = ""; this.upload= function(){ $http.post('/uploads') .then(function success(result){ self.message = "Upload worked"; }, function error(response){ self.message = "Error upload failed"; }); }; 

编辑:你应该阅读这本书: http : //www.allitebooks.com/read/index.php?id=7630

您通常从浏览器向服务器发出请求,而不是其他方式。 我build议使用Ajax进行轮询。 如果你坚持从服务器发送请求到浏览器,你可以使用Comet (但我不build议这个解决scheme)。

用jQuery(虽然在你的问题中没有提到),你可以写下这样的内容来每隔x秒轮询一次:

 function doPoll() { $.ajax({ url: "/uploads", type: "POST", data: { //Set an empty response to see the error xml: "<response></response>" }, dataType: "text xml", success: function(xml, textStatus, xhr) { if (xhr.status == "200") { //do the thing you wanted to do on succes } }, complete: function(xhr, textStatus) { console.log(xhr.status); } }); setTimeout(doPoll,5000); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>