如何将功能从客户端传递到服务器(nodejs)

时间:2019-11-11 04:14:53

标签: javascript node.js browser server client

我有此代码:

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

基本上,此代码在Node上创建本地服务器并打开文件:'index.html'。
现在,我在'index.html'上创建一个<button>,当单击(onclick)时,它将调用一个名为'hello'的函数:

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

因此,当单击按钮时,浏览器控制台中将显示一个“ hello world”,但我希望在nodejs控制台而不是浏览器中显示“ hello world”。
我该如何实现?
谢谢!

1 个答案:

答案 0 :(得分:1)

您可以使用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>