如何将后端错误/成功消息从Node.js发送到AngularJS控制器的前端?

我有一个build立在MEAN堆栈上的应用程序,带有Expressjs。

需要将成功或错误消息从后端(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控制器?

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

你应该使用socket.io

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

连接的任何一端都可以“发射”一条消息,并将消息发送到另一端。 后端可以将消息发送给所有客户端或特定的消息。 您将设置Angular来接收消息并创build一个或多个控制器可以监听的自己的事件。 请参阅https://github.com/btford/angular-socket-io当前端想要将消息发回到后端时,它可以使用套接字,或者只使用普通的HTTP POST等。

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

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

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

发生错误时,发送错误状态

 res.status(500).send(errorMsg) 

对于angular度:

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