从angular度应用程序调用nodejs中的函数

我有一个angular应用程序(angular-seed应用程序),它应该调用nodejs(web-server.js)中的一个函数。 nodejs中的函数只是调用一个batch file。

OP没有提到明确的,所以我会提供一个替代服务器端(Node.js部分),而不使用任何额外的框架(这将需要通过NPM安装)。 该解决scheme只使用节点核心:

networkingserver.js:

'use strict'; var http = require('http') var spawn = require('child_process').spawn var url = require('url') function onRequest(request, response) { console.log('received request') var path = url.parse(request.url).pathname console.log('requested path: ' + path) if (path === '/performbatch') { // call your already existing function here or start the batch file like this: response.statusCode = 200 response.write('Starting batch file...\n') spawn('whatever.bat') response.write('Batch file started.') } else { response.statusCode = 400 response.write('Could not process your request, sorry.') } response.end() } http.createServer(onRequest).listen(8888) 

假设你在Windows上,我会首先使用这样的batch file来testing它:

whatever.bat:

 REM Append a timestamp to out.txt time /t >> out.txt 

对于客户端来说,没有什么可以添加到Spoike的解决scheme 。

如果我正确地理解了这一点,你需要点击客户端(angular应用程序)来调用服务器端的batch file。 你可以根据你的要求用几种方法来实现,但基本上你希望客户端发送一个http请求到服务器(用ajax调用或者表单提交),然后在调用batch file的服务器上处理。

客户端

在客户端,你需要一个使用angular度ng-click指令的button:

 <button ng-click="batchfile()">Click me!</button> 

在您的angular度控制器中,您将需要使用$ http服务在某个特定的URL上向您的服务器发出HTTP GET请求。 url是什么取决于你如何设置你的快速应用程序。 像这样的东西:

 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... }); } } 

您可以通过使用例如您的浏览器的开发工具(如Google Chrome的networking选项卡)或http数据包嗅探器(如fiddler)来validation此HTTP GET请求。

服务器端

编辑:我错误地认为angular种子使用expressjs,它不。 请参阅basti1302关于如何设置服务器端“香草风格”node.js的答案 。 如果您使用快递,您可以继续。

在服务器端,您需要在快速应用程序中设置将执行batch file调用的URL 。 由于我们让上面的客户端向/performbatch发送一个简单的HTTP GET请求,我们将这样设置:

 app.get('/performbatch', function(req, res){ // is called when /performbatch is requested from any client // ... call the function that executes the batch file from your node app }); 

调用batch file是以某种方式完成的,但是您可以在这里阅读stackoverflow的答案以获取解决scheme:

  • node.js shell命令执行

希望这可以帮助