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

我有这个代码:


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'。

现在,我<button>在我的 'index.html' 上创建一个,当被点击 (onclick) 调用一个名为 'hello' 的函数时:


function hello() {

   console.log('hello world);

}

因此,当单击按钮时,浏览器控制台中会显示“hello world”,但我希望 nodejs 控制台中显示“hello world”,而不是浏览器。

我怎样才能实现它?


慕的地6264312
浏览 139回答 1
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) {&nbsp; &nbsp; res.sendfile('./index.html');})app.get('/getData', function (req, res) {&nbsp; &nbsp; console.log("getData called.");&nbsp; &nbsp; res.send("res from getData function");})var server = app.listen(8000, function () {&nbsp; &nbsp; var host = server.address().address&nbsp; &nbsp; var port = server.address().port&nbsp; &nbsp; console.log("Example app listening at http://%s:%s", host, port)})<html>&nbsp; <head><script>&nbsp; function httpGet(theUrl) {&nbsp; &nbsp; var xmlhttp = new XMLHttpRequest();&nbsp; &nbsp; var url = "http://localhost:8000/getData";&nbsp; &nbsp; xmlhttp.onreadystatechange = function (res) {&nbsp; &nbsp; &nbsp; if (this.readyState == 4 && this.status == 200) {&nbsp; &nbsp; &nbsp; &nbsp; document.write(this.responseText);&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };&nbsp; &nbsp; xmlhttp.open("GET", url, true);&nbsp; &nbsp; xmlhttp.send();&nbsp; }</script></head><body>&nbsp; <button onclick="httpGet()">httpGet</button></body></html>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript