onclick 函数在节点 js 中不起作用

onclick funtion is not working in node js

Node.js 停止工作 javascript 代码

我的文件结构

app.js

index.html

index.js

但是如果我 运行 它没有节点它就可以工作并且警报来了

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

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

您的服务器只提供 index.html 如果您查看 Network Tab(在代码检查器中),index.js 请求失败 您需要在需要时发送 index.js 文件。 如果你只是为此使用 Nodejs。我认为最好的是使用 expressjs 这真的很简单。

下面给出了一个最小的例子。我会推荐使用 third-party 库,例如 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);