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

问题描述 投票:0回答:2

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函数

javascript html node.js javascript-events onclicklistener
2个回答
0
投票

下面给出一个最小的例子。我建议使用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);

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.