NuzzeSicK
NuzzeSicK

Reputation: 707

How to pass function from client to server (nodejs)

I have this code:

let http = require('http');
let fs = require('fs');

let handleRequest = (request, response) => {
    response.writeHead(200, {
        'Content-Type': 'text/html'
    });
    fs.readFile('./index.html', null, function (error, data) {
        if (error) {
            response.writeHead(404);
            respone.write('Whoops! File not found!');
        } else {
            response.write(data);
        }
        response.end();
    });
};

http.createServer(handleRequest).listen(8000);

Basically, this code create a local server on Node and open the file: 'index.html'.
Now, I create a <button> on my 'index.html' that when is clicked (onclick) calls a function named 'hello':

function hello() {
   console.log('hello world);
}

So, when the button is clicked, a 'hello world' is showed in the browser console, but I want the 'hello world' to be shown in the nodejs console, not browser.
How can I achieve it?
Thanks!

Upvotes: 0

Views: 807

Answers (1)

Saurabh Agrawal
Saurabh Agrawal

Reputation: 7739

You can achieve it using nodeJS and expressJS. To install express run npm i express.

Try this

let http = require('http');
let fs = require('fs');
let express = require('express');
let app = express();
app.get('/', function (req, res) {
    res.sendfile('./index.html');
})

app.get('/getData', function (req, res) {
    console.log("getData called.");
    res.send("res from getData function");
})

var server = app.listen(8000, function () {
    var host = server.address().address
    var port = server.address().port
    console.log("Example app listening at http://%s:%s", host, port)
})
<html>
  <head>
<script>
  function httpGet(theUrl) {
    var xmlhttp = new XMLHttpRequest();
    var url = "http://localhost:8000/getData";
    xmlhttp.onreadystatechange = function (res) {
      if (this.readyState == 4 && this.status == 200) {
        document.write(this.responseText);
      }
    };
    xmlhttp.open("GET", url, true);
    xmlhttp.send();
  }
</script>
</head>
<body>
  <button onclick="httpGet()">httpGet</button>
</body>

</html>

Upvotes: 1

Related Questions