单击html按钮时如何调用node js函数? [英] how to call node js function when a html button is clicked?

查看:621
本文介绍了单击html按钮时如何调用node js函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个部署按钮,单击该按钮应将一个容器部署到我的kubernetes集群上.因此,为此,每当单击html按钮时,我想调用一个node.js文件,该文件将执行命令"kubectl apply" -f tomcat.yaml".因此,当单击html按钮时如何调用node.js文件.我听说可以使用AJAX来实现.

I want to create a deploy button,which when clicked should deploy a container onto my kubernetes clusture.So for this whenever the html button is clicked, I want to invoke a node.js file which will execute the command "kubectl apply -f tomcat.yaml".So how can I call the node.js file when the html button is clicked.I heard this can be achieved using AJAX.

HTML页面

<!DOCTYPE html>
<html>
<body>
    <h3>Example of a Deploy and Decommission Button</h3>
    <button onclick="myFunction()">Deploy</button>
    <button onclick="myFunction()">Decommission</button>
</body>
</html> 

运行kubectl命令的node.js文件

node.js file that runs the kubectl command

var process = require('child_process');
process.exec('kubectl apply -f tomcat.yaml',function (err,stdout,stderr) {
    if (err) {
        console.log("\n"+stderr);
    } else {
        console.log(stdout);
    }
});

如果有人可以向我展示如何在单击按钮时调用我的代码作为我的个人理解示例,那么我将如何为它调用node.js文件. 我听说可以使用AJAX调用服务器端代码或获取请求.但是有人可以通过使用我的html和node.js文件为示例向我展示示例.请帮忙.

It would me helpful if someone can show me how to call the node.js file upon button click using my code as example for my personal understanding. I heard that server side code can be called using AJAX or get request.But can someone show me an example by using my html and node.js file as example.Kindly help please.

推荐答案

您可以在nodejs中使用express like作为终点

You can just make an end point in nodejs with express like

    const app = require("express")();
    const process = require('child_process');
    app.post("/createContainer", (req, res) => {
     process.exec('kubectl apply -f tomcat.yaml',function (err,stdout,stderr) {
      if (err) {
        console.log("\n"+stderr);
      } else {
        console.log(stdout);
      }
    });
   });
   app.list(80);

完成后,您只需在正面拨打AJAX呼叫

When you did it you just have to make an AJAX call in front side

$("#myBtn").click(() => {
  $.post("/createContainer").done(() => {
   console.log("container created")
  });
});

这篇关于单击html按钮时如何调用node js函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆