html - 从 html 单击按钮调用 Nodejs 脚本
问题描述
我想从我的 html 提交按钮调用特定的 nodejs 脚本。
我有工作的客户端-服务器端代码,但我想改进我的 html-to-client-side 以调用 nodejs 脚本。
服务器端.js
console.log('Server-side code running');
const app = express();
const port = 80;
// serve files from the public directory
app.use(express.static('public'));
// serve the homepage
app.listen(port, () => {
console.log('Server is listening on port: %s', port);
});
app.get('/', (req, res) => {
res.sendFile(__dirname + '/htmlcode.html');
});
app.post('/clicked', (req, res) => {
const click = {clickTime: new Date()};
console.log(click);
fs.open('testfile.txt', 'w', (err) => {
if (err) throw err;
console.log('Saved!');
});
});
htmlcode.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<h1>Example</h1>
<button id="myButton">Submit</button>
</body>
<script src="toclient.js"></script>
</html>
toclient.js
console.log('Client-side code running');
const button = document.getElementById('myButton');
button.addEventListener('click', (err) => {
console.log('button was clicked');
fetch('/clicked', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
我想将调用 nodejs 的 html 按钮改进为类似于 onClick 的东西。(基本上点击提交按钮,执行toclient.js)
解决方案
看起来您只是在前端使用纯 JavaScript。您应该考虑使用像 angular 或 angularjs 这样的框架
推荐阅读
- python - Python 数据框 if 和 for 语法错误
- python - Python通过特定列中的条件定义函数来子集数据帧
- java - 无法在 Java 中获得类似金字塔的图像
- python - 如何断开 Gmail API 服务实例?
- javascript - 我收到警告 Synchronous XMLHttpRequest without set async false
- html-table - 下面的 $row['imageData'] 代码不显示图像
- tensorflow - CUDA/TensorFlow 兼容性
- python - Pandas:如果字段中的值为 None/null/NaN,则将该字段的名称附加到新字段
- python - FastAPI 中间件窥探响应
- python - 如何使用它们的绝对值对包含复数的列表进行排序?