Kod*_*ode 2 node.js express angularjs
让我以前缀为Node/Express更新.
我有一个AngularJS应用程序利用Node.JS来管理Azure Blob要求,例如创建Blob容器,如下所示:
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');
Run Code Online (Sandbox Code Playgroud)
从Node中的server.js执行时创建容器的功能按预期工作并创建一个blob容器.但是,我需要在我的AngularJS应用程序中单击创建一个blob容器.我设想使用导出来访问和执行在Server.js中创建的函数,但是已经看到一些混合信息,特别是当Express.js在图片中时,用于通过AngularJS客户端调用Node.js函数,因为它似乎在Angular App中必须进行http调用(请参阅本文中的最后一个答案:来自angular应用程序的nodejs中的调用函数).
我的问题如下:
1)由于我的应用程序当前使用Node,Express和Angular,我是否需要在Angular控制器中使用http运行Node函数/执行Node/Server中编写的所有函数.如果通过AngularJS客户端调用,则需要$ http执行即使他们不打电话给服务,但可能是执行诸如数学之类的功能?基于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...
});
}
}
Run Code Online (Sandbox Code Playgroud)
2)或者正在使用导出,例如本文中列出的更常见的做法,其中函数被定义为导出然后通过需求导入:Node.js module.exports的用途是什么以及如何使用它?.如果是这样,我会做以下事情吗?:
Node Server.JS文件:
var myFunc1 = function() { ... };
exports.myFunc1 = myFunc1;
Run Code Online (Sandbox Code Playgroud)
在AngularJS控制器中(不包括作为依赖项):
var m = require('pathto/server.js');
m.myFunc1();
Run Code Online (Sandbox Code Playgroud)
3)最后,我完全偏离基础,并且有一个常见的做法是从我失踪的Angular Controller调用node.js函数?
首先,nodejs和angularjs都是javascript都是两个不同的实现.
NodeJS在服务器上工作,另一方面,angularjs在浏览器上工作.
最初当我是节点的新手我也有同样的问题.我以为我们可以直接从angularjs调用节点函数,毕竟一切都是正确的!但是我错了..
现在,您应该如何做到这一点
首先在nodejs中创建一个路由(没什么,只需创建一个简单的restAPI)
app = express();
app.get('/dowork',function(res,req){
console.log(req.params.msg);
/... code to do your work .../
});
Run Code Online (Sandbox Code Playgroud)
现在在angularjs呼叫做工作
$http.get('http://localhost:8080/dowork',{"msg":"hi"}).success(function(data){
console.log(data);
});
Run Code Online (Sandbox Code Playgroud)
我不确定它,req.params.msg但你可以登录,req并可以找到该对象.
如果是邮寄请求,您的参数将在 req.body