从页面的JavaScriptbutton运行Node.JS

我想要做什么:用户单击网页上的button,它执行一个node.js脚本,在node.js页面上执行服务器端操作。

示例:每当有人点击页面中的button,Node.js就会在服务器控制台上输出一条消息。

我可以做的到目前为止:我可以用node.js + express来展示一个页面。 我只是不能让服务器端的行动发生。

<button type="button" onclick="testF()">Click</button> <script> function testF(){ alert('Hello world!'); console.log('clicked!!'); //Id like this to show on the node.js console } </script> 

谢谢!

你不需要使用快递。 Node.js非常简单。

根据其他成员,你必须使用AJAX,所以… jQuery也不是必需的。

看看我为你制作的代码(只记得我做了一个非常弱的代码,因为如果我写一个更安全的代码可能会比你期望的大)。

的test.html

 <button type="button" onclick="testF()">Click</button> <script> function testF() { alert('Hello world!'); var xmlhttp = new XMLHttpRequest(); xmlhttp.open("get", "/service"); xmlhttp.onreadystatechange = function() { // DONE if (xmlhttp.readyState == 4) { switch(xmlhttp.status) { case 200: alert("OK"); break; case 404: alert("Not Found"); break; case 500: alert("Internal Server Error"); break; default: alert("Unexpected Error. HTTP Status: " + xmlhttp.status); } } }; xmlhttp.send(); } </script> 

server.js (Node.js)

 var nsHttp = require("http"); var nsUrl = require("url"); var nsPath = require("path"); var nsFs = require("fs"); var srv = nsHttp.createServer(function(req, res) { var pathname = nsUrl.parse(req.url).pathname; // check URL to send the right response switch(pathname) { case "/favicon.ico": res.end(); break; case "/": HTTP_SendHtmlFile(res, nsPath.join(__dirname, "test.html")); break; case "/service": console.log("clicked!"); HTTP_SendOK(res, ""); break; default: HTTP_SendNotFound(res); } }); // reads a file contents and sends, but if any error occur, // sends a 500 HTTP Status Code (Internal Server Error) function HTTP_SendHtmlFile(res, filepath) { nsFs.readFile(filepath, function(err, data) { if (err) { HTTP_SendInternalServerError(res); return; } HTTP_SendOK(res, data); }); } function HTTP_SendOK(res, body) { res.writeHead(200, {"Content-type": "text/html"}); res.end(body); } function HTTP_SendInternalServerError(res) { res.writeHead(500, {"Content-type": "text/html"}); res.end(); } function HTTP_SendNotFound(res) { res.writeHead(404, {"Content-type": "text/html"}); res.end(); } srv.listen(8080);