Search code examples
node.jsraspberry-piwebserver

Run nodejs functions from a web server


I'm running a web server on raspberry pi and I want to call a node.js function when clicking on a button on a page. Is there a way of doing that?


Solution

  • Yes.

    You need to have a Node app listening on some port on your server. The simplest way would be to have a very simple Express app, for example:

    var app = require('express')();
    
    app.post('/some/path', function (req, res) {
        // call your function here
    });
    
    app.listen(3000, function () {
      console.log('Listening on port 3000');
    });
    

    Now, in your HTML you need to make a POST request to http://YOURDOMAIN:3000/some/path to call your function (for example using a form or an AJAX request).

    If you're using a webserver like nginx then you can proxy requests to your app so that your app won't have to access under different port and/or domain than your main website.