简体   繁体   中英

Tell Node.js server to run a function by using javascript in html

I'm trying to send the command to execute a function in Node.js from an html Button and don't really know where to start.

So I'm currently working on a website that should be able to control my raspberry pi's GPIO pins and send commands to another Linux-Based Computer in the raspberry's network.

I already have the functions to do the above completed in javascript and it works perfectly fine when executed in Node.js. The only Problem is, that when directly implemented into an html, the code is not executed on the raspberry but in the browswer. I now know I'll have to host a Node.js server on the Raspberry and send commands to that. But that exactly is my problem.

server.js:

function serverShutdown() {

    { some working code }

}

index.html:

<html>
    <head>
        <script src="../scripts/client.js"></script>
    </head>
    <body>

        <div class="ButtonClass">
            <button onclick="server_shutdown()">Herunterfahren</button>
        </div>
    </body>
</html>

client.js:

function server_shutdown() {

    ? ? ?

}

I think you need the http module in your server side app to handle an http request from a client to your server.

You could look at this link: https://nodejs.dev/the-nodejs-http-module

From the client side you should call an url that the server could handle. Or you need to create an event handler on the server side. More informations at: https://www.npmjs.com/package/events

Moreover your server should have module that exports the methods you need.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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