Call a node.js function inside an html file

Issue

This is most likely a repeated question.

The closest I got to an answer was here: execute a Nodejs script from an html page?

Yet, I still can’t understand.

So here’s the situation:

I have an express server setup with the following files:

  • Express App

    server.js
    index.html

and right now I want the html folder to have a button, that calls a function set in the node.js file.

Tell me if more information is needed, thanks!

EDIT:
Im remaking the question to be more clear.

I am using an express server to present a website, that present a button saying ” Power Off”, I want this button to be able to execute an action on my server computer, that action being a terminal command to power it off.

I wanted to know how could I make said button, written in HTML, hosted on the server but presented to the client, to interact with the server.js file hosted on the server, which would have a function set to execute said command.

thanks!

Solution

You need to understand a little better how the client/server architecture of a web page works and where code actually runs and how the client and server communicate with one another.

You can’t call a function directly on your node.js server from an HTML file. The HTML file is in the client’s browser. The node server is your web server, far away from the client’s browser on different computers. Though it may seem like your HTML is on your node.js server because it’s in a directory on that server, that’s only where it is stored. When the browser requests that page, your node.js server sends the HTML to the client’s browser and it is rendered back in the client browser and that’s where the Javascript in that page runs (in the client’s browser, far away from your node.js server). This is a client-server architecture. The HTML page is running on the client. The node.js server is on your server – different computers.

If you want to communicate with the node.js server from the web page, then you use Javascript in the HTML page to make an Ajax call from the Javascript in the web page to the node.js server (An Ajax call is an http request). You then configure a route in the node.js server for that specific Ajax call and you can then write code in node.js to do whatever you want to happen when that Ajax call is received. It can carry out some operation on the server, it can retrieve data and return it to the client, etc… You can optionally send data with the Ajax call (either as query parameters for a GET request or as body data for a POST request) and then the server can optionally return data back to you (often as JSON, but it can be any format you like).

Answered By – jfriend00

Answer Checked By – David Marino (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.