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函数
下面给出一个最小的例子。我建议使用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);
您的服务器仅提供index.html
如果您查看Network Tab(在代码检查器中),则index.js请求失败您需要在需要时发送index.js文件。如果仅使用Nodejs。我认为最好是使用expressjs,这真的很容易。