Вызов скрипта Nodejs с помощью кнопки HTML - PullRequest
0 голосов
/ 11 июля 2019

Я хочу вызвать определенный скрипт nodejs из моей кнопки отправки в html.

У меня есть работающий клиент-серверный код, но я хочу улучшить свою 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 голосов
/ 11 июля 2019

Похоже, вы просто используете простой JavaScript на передней части.Вы должны изучить использование таких рамок, как angularjs или angularjs

...