【问题标题】:Run JS function on Node server after OnClick event in HTML [duplicate]在 HTML 中的 OnClick 事件之后在节点服务器上运行 JS 函数 [重复]
【发布时间】:2018-10-06 07:55:25
【问题描述】:

我在 Windows 上使用 node.js,通过 express 模块生成一个静态页面,其中包含我想要的提交表单当有人点击“提交”按钮时,在服务器上运行 update() 函数(即不公开我的 js 文件)。

问题:

我的update() 函数似乎无法从 HTML 中识别出来。产生如下错误:

未捕获的引用错误:未定义更新 在 HTMLInputElement.onclick ((index):23)

我怀疑这是我的节点项目设置不正确的结果。


服务器文件(server.js):

var fs = require('fs');
var express = require("express");
var app     = express();

app.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});

//loading all files in public folder
//see instructions in https://expressjs.com/en/starter/static-files.html
app.use(express.static('public'));

app.listen(8080);

console.log("Running at Port 8080");

HTML 文件 (index.html):

<!DOCTYPE html>
<html>

<body>

<div id="div1">
  <p id="p1">This is a static paragraph.</p>
</div>

<p>
  <script type="text/javascript" src="start.js"></script>
</p>

Input:
<br>
<input type="text" name="human_input" value="">
<br>
<input type="button" value="Submit" onclick="update()">

</body>
</html>

JS 文件(compute.js)

function update() {
    console.log("this is running!")
}

^^ 注意,这是我正在尝试使用的示例脚本。

我的文件夹结构

/
- node_modules
-- *
- public
-- start.js
- index.html
- compute.js
- package-lock.json
- server.js
- start.js

注意事项:

  • 以前我不使用节点时,从 onclick 调用 update() 是有效的。

【问题讨论】:

  • 节点运行在服务器端。您要做的是客户端执行。
  • 也许您应该在您的index.html 中要求compute.js 文件?看来您只需要start.js?但是,如果您不希望节点服务器端进行通信,您将需要诸如 http、web 套接字或类似的传输。
  • @PavanAndhukuri,这是有道理的。我很高兴为服务器端执行重构我的代码。第一步是什么?或者是否有您可以提供的文档链接?
  • @nijm 你是对的,这让代码在客户端工作。我编辑了这篇文章以获得将代码从客户端移动到服务器端的一些帮助。但如果您有任何文档,我们很乐意查看。

标签: javascript html node.js express


【解决方案1】:

您错过了指向compute.js 文件的html 文件中的script 标记,这就是您的update 不起作用的原因。

只需复制您在 html 文件中已有的 script 并将 src 属性更改为 compute.js 值

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-09
    • 2020-03-06
    • 2020-07-24
    • 1970-01-01
    • 1970-01-01
    • 2017-04-27
    相关资源
    最近更新 更多