javascript - onclick 函数在 Node js 中不起作用

标签 javascript html node.js dom-events onclicklistener

Node.js 停止运行 JavaScript 代码

我的文件结构

app.js

index.html

index.js

但是如果我在没有 Node 的情况下运行它,它就可以工作并且会发出警报

app.js

var http = require('http');
var fs = require('fs');

const PORT=80; 

fs.readFile('./index.html', function (err, html) {
    if (err) throw err;    
    http.createServer(function(request, response) {  
console.log(request.addListener.name);
        response.writeHeader(200, {"Content-Type": "text/html"});  
        response.write(html);  
        response.end();  
    }).listen(PORT);
    console.log(`Server running at http://127.0.0.1/`);
});     

index.html

<html>
<head>
<script src="index.js"></script>
</head>
<body>
<button onclick="start()">onclick</button>
</body>
</html>

index.js

function start(){
alert('start');
}

任何人,请建议我解决方案,当我在 Node 上运行时,如何通过单击按钮或更改输入数据来调用 Javascript 函数。

最佳答案

下面给出了一个最小的示例。我建议使用第三方库,例如 express-js创建服务器。

const http = require("http");
const fs = require("fs");
const path = require("path");
const PORT = 8080;
http
  .createServer(({ url }, response) => {
    response.setHeader("Content-Type", "text/html");
    if (url == "/") fs.createReadStream("./index.html").pipe(response);
    else {
      const filePath = path.join(__dirname, url);
      const stats = fs.existsSync(filePath);
      if (stats) fs.createReadStream(filePath).pipe(response);
    }
  })
  .listen(PORT);

关于javascript - onclick 函数在 Node js 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61140496/

相关文章:

javascript - 在选择合适的 iOS Mobile Safari Web 开发工具(jQuery Mobile/Sencha Touch/等)时感到沮丧

javascript - AjaxFileUpload 添加 OnClientUploadCompleteAll 破坏布局

php - 支付宝成功返回网址

javascript - AngularJS $interval 自动停止

javascript - 正则表达式不能在 c# 中工作,但可以在 javascript 中工作

javascript - IE 8 自动关闭 &lt;header&gt; 标签

html - 导航栏不显示子菜单

javascript - React.js 使用 axios 发送整数数据但在 Node.js 中获取 [object object]

mongodb - 如何使用 Mongoose 执行 runCommand?

node.js - 导出动态变量