如何发送后端的错误/成功的消息从Node.js的在AngularJS控制器前端? [英] How to send backend errors/success messages from Node.js to frontend in AngularJS controller?

查看:251
本文介绍了如何发送后端的错误/成功的消息从Node.js的在AngularJS控制器前端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经建立了MEAN堆栈上的应用程序,与前pressjs。

I have an application built on the MEAN stack, with Expressjs.

有必要从后端(的NodeJS)发送成功或错误信息发送到前端(angularjs) - 例如显示,当一个文件被成功上传。下面 - 在 app.post 被成功地完成了,我想显示在前端(在AngularJS)这个结果

There is a need to send success or error messages from backend (nodejs) to frontend (angularjs) for example - to show when a file was successfully uploaded. Below - after app.post is succesfully completed, I would like to show this result on frontend (in 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控制器什么办法?

Is there any way that I can send the result from NodeJS to AngularJS controller?

有一个类似的问题<一href=\"http://not%20http://stackoverflow.com/questions/18058566/how-to-send-data-from-node-js-to-angular-js-controller\">here,但没有解决。

There is a similar question here, but unsolved.

推荐答案

刚刚复出利用资源对象发送一个HTTP响应:

Just send a http response back using the res object :

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

当错误,发送一个错误状态

When error, send, a error status

res.status(500).send(errorMsg)

有关角:

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

这篇关于如何发送后端的错误/成功的消息从Node.js的在AngularJS控制器前端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆