【问题标题】:How to send backend errors/success messages from Node.js to frontend in AngularJS controller?如何将后端错误/成功消息从 Node.js 发送到 AngularJS 控制器中的前端?
【发布时间】:2016-01-10 21:12:32
【问题描述】:

我有一个使用 ExpressJS 构建在 MEAN 堆栈上的应用程序。

例如,需要从后端 (NodeJS) 向前端 (AngularJS) 发送成功或错误消息 - 以显示文件何时成功上传。下面 - 在app.post 成功完成后,我想在前端(在 AngularJS 中)显示这个结果。

app.post('/upload' , function (req, res) {
        //busboy handles multi-part file upload
        console.log('Post received to upload ...');

        var fstream;

        req.pipe(req.busboy);

        req.busboy.on('file', function (fieldname, file, filename) {
            //only update if the filename was change or exists
            if (filename!== undefined || filename !=='') {
                  //reset url
                  options.url = '';
                 console.log("Uploading the file " + filename);
                  console.log("before", options);
                  options.path = '/uploads/'  + filename;
                  options.fileName = filename; //update file name

                  console.log("Updating options ...", options);
                  fstream = fs.createWriteStream(__dirname + '/uploads/' + filename); //path where the file will be uploaded
                  file.pipe(fstream);
                  fstream.on('close', function () {
                      console.log("Upload finished successfully ! Uploaded " + filename);
                      initOntology();//initialize the ontology from upload
                      initEdges();
                  });
            }

        });
});

有什么方法可以将结果从 NodeJS 发送到 AngularJS 控制器?

有一个类似的问题here,但没有解决。

【问题讨论】:

    标签: angularjs node.js


    【解决方案1】:

    你应该使用 socket.io

    当前端启动时,它会连接到一个“套接字连接”。这是与 HTTP 不同的协议。如果它不能这样做,它会使用通过 HTTP 工作的降级版本的连接。

    连接的任何一端都可以“发出”一条消息,该消息会被发送到另一端。后端可以向所有客户端或特定客户端发送消息。您将设置 Angular 来接收消息并创建一个或多个控制器可以监听的自己的事件。见https://github.com/btford/angular-socket-io当前端想给后端发回消息时,可以使用socket,也可以只是普通的HTTP POST等。

    在 Angular 和 Node 中使用它是相当标准的,应该有很多关于如何做到这一点的信息。

    【讨论】:

    • 我认为只要中间件的 res 对象的结果就可以完成这项工作,angularjs 会收到一个简单的 http 响应。
    • 对不起,我不确定你的意思@MoncefHassein-bey
    • 为什么要使用套接字?她可以做到:res.status(200).send('OK')
    • 这听起来更容易。如果出现错误,我会发送什么响应? (对于相同的文件上传示例?)
    • 你应该添加一个答案@MoncefHassein-bey
    【解决方案2】:

    只需使用 res 对象发送一个 http 响应即可:

    res.status(200).send('OK') 
    

    出错时,发送,错误状态

    res.status(500).send(errorMsg)
    

    对于角度:

    $http.post(...).then(function successCallback(response) {
          // response with 200 status
          }, function errorCallback(response) {
          // response with status 500
      });
    

    【讨论】:

    • “发送后无法设置标头”这是我尝试使用 res.status 响应时出现的 node.js 错误。
    猜你喜欢
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2018-11-10
    • 1970-01-01
    • 2018-11-02
    • 1970-01-01
    • 2017-02-04
    • 2013-01-30
    相关资源
    最近更新 更多