首页 > 解决方案 > 从 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)

标签: htmlnode.jsclickclient-server

解决方案


看起来您只是在前端使用纯 JavaScript。您应该考虑使用像 angular 或 angularjs 这样的框架


推荐阅读