从Angular Controller调用节点函数的常用方法

让我加上这个,我更新Node / Express。

我有一个AngularJS应用程序,利用Node.JS来pipe理Azure Blob需求,例如创buildBlob容器,如下所示:

function test(containerName) { blobSvc.createContainerIfNotExists(containerName, function (error, result, response) { if (!error) { // Container exists and allows // anonymous read access to blob // content and metadata within this container } }); }; test('blob4'); 

从Node中的server.js执行时创build容器的函数按预期工作,并创build一个blob容器。 不过,我需要在AngularJS应用程序中单击创build一个blob容器。 我设想使用导出来访问和执行在Server.js中创build的函数,但看到一些混合的信息,尤其是当Express.js在图片中时,通过AngularJS客户端调用Node.js函数,因为它似乎在一个Angular应用程序必须进行http调用(请参阅本文中的最后一个答案: 从angular度应用程序调用nodejs中的函数 )。

我的问题如下:

1)由于我的应用程序当前使用Node,Express和Angular,我需要使用我的Angular控制器中的http来运行Node函数/如果通过AngularJS客户端调用,Node / Server.js中编写的所有函数都需要执行$ http即使他们不打电话服务,但可能是执行诸如math的function的function? 基于Express的呼叫示例:

 function MyCtrl($scope, $http) { // $http is injected by angular's IOC implementation // other functions and controller stuff is here... // this is called when button is clicked $scope.batchfile = function() { $http.get('/performbatch').success(function() { // url was called successfully, do something // maybe indicate in the UI that the batch file is // executed... }); } } 

2)或者正在使用导出,比如本文中列出的更常见的做法,其中函数被定义为导出,然后通过一个require导入: Node.js module.exports的用途是什么,你如何使用它? 。 如果是这样,我会做类似以下的事情吗?

节点Server.JS文件:

 var myFunc1 = function() { ... }; exports.myFunc1 = myFunc1; 

在AngularJS控制器(不包括作为依赖项)中:

 var m = require('pathto/server.js'); m.myFunc1(); 

3)最后,我完全脱离基地,并从我失踪的angular度控制器调用node.jsfunction的常见做法?

首先nodejs和angularjs都是javascript都是两个不同的实现。

NodeJS在服务器上工作,另一方面angularjs在浏览器上工作。

最初当我是新手到节点我也有同样的问题。 我想我们可以直接从angularjs调用节点函数,毕竟一切都是JavaScript的权利! 但是我错了..

现在在这里你应该如何做到这一点

首先在nodejs中创build一个路由(它没有什么,只是创build一个简单的restAPI)

 app = express(); app.get('/dowork',function(res,req){ console.log(req.params.msg); /... code to do your work .../ }); 

现在在angularjs调用做工作

 $http.get('http://localhost:8080/dowork',{"msg":"hi"}).success(function(data){ console.log(data); }); 

我不知道它会req.params.msg但你可以loggingreq并可以find对象。

在post请求的情况下你的参数将在req.body