【问题标题】:How to pass function from client to server (nodejs)如何将功能从客户端传递到服务器(nodejs)
【发布时间】:2019-11-11 04:14:53
【问题描述】:

我有这个代码:

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”,而不是浏览器。
我怎样才能实现它?
谢谢!

【问题讨论】:

  • .js 文件中创建一个 post/get 请求,然后从 html 调用它。
  • 你能把代码发给我吗?我是菜鸟:(
  • 对不起,我试过了,但我做不到

标签: javascript node.js browser server client


【解决方案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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-15
    • 1970-01-01
    • 2016-11-12
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 2016-11-28
    • 1970-01-01
    相关资源
    最近更新 更多