Как передать функцию от клиента к серверу (nodejs) - PullRequest
0 голосов
/ 11 ноября 2019

У меня есть этот код:

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);

По сути, этот код создает локальный сервер на узле и открывает файл: «index.html».
Теперь я создаю <button> в моем index.html, который при нажатии (onclick) вызывает функцию с именем 'hello':

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

Итак, когда кнопка нажата,«hello world» отображается в консоли браузера, но я хочу, чтобы «hello world» отображался в консоли nodejs, а не в браузере.
Как мне этого добиться?
Спасибо!

1 Ответ

1 голос
/ 11 ноября 2019

Вы можете достичь этого, используя nodeJS и expressJS . Чтобы установить экспресс-запуск npm i express.

Попробуйте это

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>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...