简体   繁体   English

如何通过单击 html 中的按钮来运行节点 js 文件(进行 api 调用并将数据放入工作表中)

[英]How to run a node js file (that makes a api call and puts data into a sheet) by clicking on a button in html

I tried to get some answers here on stack overflow but I don't really understand it.我试图在这里得到一些关于堆栈溢出的答案,但我不太明白。

I want to execute my node js script by clicking on a button in html.我想通过单击 html 中的按钮来执行我的节点 js 脚本。 The node js file pulls data from an excel sheet and puts it into a specific sheet.节点 js 文件从 excel 工作表中提取数据并将其放入特定工作表中。

The node js file works perfectly if I run it in the console.如果我在控制台中运行节点 js 文件,它可以完美运行。 But how do I connect this file with a button in html?但是如何将此文件与 html 中的按钮连接? It is not possible just to call the function, because the node js file is running on a server.不能只调用 function,因为 node js 文件是在服务器上运行的。

This is the function I want to execute by clicking on a button这是我想通过单击按钮执行的 function

function importData(){
    //import the smartsheet
    ss.sheets.importXlsxSheet(options)
    .then(function(result) {
        console.log("Created sheet '" + result.result.id + "' from excel file");
        
        // Load entire sheet
        ss.sheets.getSheet({ id: result.result.id })
            .then(function(sourceSheet) {
                console.log("Loaded: " + sourceSheet.rows.length + " rows from sheet '" + sourceSheet.name + "'");
                console.log("Done");

                    //copy every row from sourcesheet in a array 
                    const sourceSheetRows = sourceSheet.rows;
                    writeRowsinArray(result, sourceSheetRows);
            })
            .catch(function(error) {
                console.log(error);
            });
    })
    .catch(function(error) {
        console.log(error);
    });
}

The standard way to trigger something on a server from a browser is to make an HTTP request to it.从浏览器触发服务器上某些东西的标准方法是向它发出 HTTP 请求。

So set up an HTTP endpoint that will trigger the function (eg by running a server built around the express module or using a cloud service such as AWS Lambda) then use client-side JS to make the request (eg with the Fetch API).因此,设置一个 HTTP 端点,它将触发 function(例如,通过运行围绕 express 模块构建的服务器或使用 AWS Lambda 等云服务),然后使用客户端 JS 发出请求(例如,使用 Fetch API)。

You have to call an exposed api for that.为此,您必须调用暴露的 api。 Your nodeJs script have to listen on an endpoint.您的 nodeJs 脚本必须在端点上侦听。

From JavaScript in your html you have to call your api using fetch .从 html 中的 JavaScript 开始,您必须使用fetch调用 api 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM