从HTML单击按钮调用Node.js脚本

时间:2019-07-11 16:05:14

标签: html node.js click client-server

我想从html提交按钮中调用特定的nodejs脚本。

我有有效的客户端-服务器端代码,但我想改进自己的html-to-client-side来调用nodejs脚本。

serverside.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)

1 个答案:

答案 0 :(得分:0)

您似乎只是在前端使用纯JavaScript。您应该考虑使用诸如angular或angularjs之类的框架