html - 从nodejs后端发送回调到前端

标签 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";
        });
  };

最佳答案

编辑:你应该读这本书: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>

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

You should think of it like this: a browser is meant to make stateless requests, not to keep open a connection, however with commet or websockets it's possible. With polling which I would recommend you ask the server a lot of times for the info until you get the desired response.

来自关于 Comet 的 wiki:

None of the above streaming transports work across all modern browsers without negative side-effects. This forces Comet developers to implement several complex streaming transports, switching between them depending on the browser. Consequently, many Comet applications use long polling, which is easier to implement on the browser side, and works, at minimum, in every browser that supports XHR. As the name suggests, long polling requires the client to poll the server for an event (or set of events). The browser makes an Ajax-style request to the server, which is kept open until the server has new data to send to the browser, which is sent to the browser in a complete response. The browser initiates a new long polling request in order to obtain subsequent events. Specific technologies for accomplishing long-polling include the following:

关于html - 从nodejs后端发送回调到前端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39208467/

相关文章:

javascript - 如何在功能上加入延迟?

javascript - 如何修改 node.js 流

c# - 跨线程互斥?

javascript - 如何避免出现这种 "eventual callback"模式?

html - 在固定宽度跨度旁边显示表格

javascript - HTML5 Canvas 游戏静态实体元素

node.js - 从 MEAN 堆栈开始,只是咕哝

javascript - 多变量 socket.io 发出的问题

javascript - Node.js 表搜索因使用中的 Promise 失败

html - Chrome 中的 Media print.css 不打印 html 内容