【问题标题】:onclick funtion is not working in node jsonclick 函数在节点 js 中不起作用
【发布时间】:2020-04-10 12:43:23
【问题描述】:

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.js

标签: javascript html node.js dom-events onclicklistener


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2021-03-21
      • 2021-11-27
      • 2016-04-16
      • 1970-01-01
      • 1970-01-01
      • 2016-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多