javascript - 从 Angular 应用程序调用nodejs中的函数

标签 javascript html node.js angularjs request

我有一个 Angular 应用程序( Angular 种子应用程序),它应该调用 nodejs(web-server.js)中的一个函数。 nodejs中的函数只是调用一个批处理文件。

最佳答案

如果我理解正确,您需要在客户端( Angular 应用程序)上单击以调用服务器端的批处理文件。您可以根据您的要求以多种方式执行此操作,但基本上您希望客户端向服务器发送 http 请求(使用 ajax 调用或表单提交)并在将调用批处理文件的服务器上处理它.

客户端

在客户端,您需要有一个使用 Angular ng-click 的按钮指令:

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

在您的 Angular Controller 中,您需要使用 $http service在某个特定的 url 上向您的服务器发出 HTTP GET 请求。该 url 是什么取决于您如何设置 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...
        });
    }

}

您可以验证此 HTTP GET 请求是通过使用例如您浏览器的开发人员工具,例如 Google Chrome's network tab或 http 数据包嗅探器,例如 fiddler .

服务器端

编辑:我错误地认为 angular-seed 使用的是 expressjs,但事实并非如此。参见 basti1302's answer on how to set it up server-side "vanilla style" node.js .如果您使用的是 Express,则可以在下面继续。

在服务器端你需要set up the url in your express app这将执行批处理文件调用。由于我们让上面的客户端向 /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
});

调用批处理文件是通过某些方式完成的,但您可以在此处阅读 stackoverflow 答案以获取解决方案:

希望对你有帮助

关于javascript - 从 Angular 应用程序调用nodejs中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18327039/

相关文章:

javascript - 如何在 javascript 的以下代码中优化对数组的处理?

javascript - 如何使用webpack将我的JavaScript库代码打包为jQuery一样可扩展?

javascript - 如何在点击时使用初始 useState 值

html - DIV 100% 在 DIV 内,保持页脚粘性

jquery - 如果可能的话,如何使用 jquery 和/或 bootstrap 制作可切换的 div 以进行多种选择?

javascript - 如何将 Discord.js 和 twit 相互集成,以在指定 channel 上进行实时 Twitter 提要

javascript - HTML5 Canvas 游戏生成间隔

javascript - 在按钮组中获取事件按钮( Bootstrap )

node.js - 如何使用无服务器框架引用不在根文件夹中的函数?

javascript - 是否可以使用 Kotlin 构建完整的 Node.js Web 应用程序?