0

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!

3
  • Create a post/get request in your .js file and then call it from html. Commented Nov 11, 2019 at 4:23
  • can you send me the code or something? i'm a noob :( Commented Nov 11, 2019 at 4:24
  • sorry, i tried but i can't achieve it Commented Nov 11, 2019 at 4:41

1 Answer 1

1

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.