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/