从nodejs后端发送回调到前端

时间:2016-08-29 14:15:44

标签: html node.js callback response

我有一个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";
        });
  };

1 个答案:

答案 0 :(得分:1)

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

您通常会从浏览器向服务器发出请求,而不是相反。我建议使用Ajax进行轮询。如果您坚持要求服务器向浏览器发送请求,您可以使用Comet(但我不建议使用该解决方案)。

使用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>

P.S。完全忘了sockets我也喜欢这个解决方案,但要注意套接字不像HTTP那样是REST。

  

你应该这样想:浏览器意味着无国籍   请求,不要保持打开连接,但与commet或   websockets它是可能的。通过民意调查,我建议你问   服务器很多次都是为了获得所需的信息   响应。

关于Comet的维基:

  

以上所有流式传输都不适用于所有现代浏览器   没有负面的副作用。这迫使彗星开发商   实现几个复杂的流传输,在它们之间切换   取决于浏览器。因此,许多Comet应用程序都在使用   长轮询,在浏览器端更容易实现,和   至少在每个支持XHR的浏览器中都有效。作为名称   建议,长轮询要求客户端轮询服务器   事件(或事件集)。浏览器发出Ajax样式的请求   服务器,在服务器有新数据要发送之前保持打开状态   到浏览器,以完整的响应发送到浏览器。   浏览器启动新的长轮询请求以获取   随后发生的事件。完成的具体技术   长轮询包括以下内容: