如何使用节点 js 的功能在 html 中的按钮中使用约翰尼五?

How to use a function of nodejs to use in a button in html for use joohny five?

我使用带有 express 的 nodejs 创建了一个服务器

server.js

const express = require('express');
const app = express();
const path = require('path');
const router = express.Router();
router.get('/',function(req,res){
  res.sendFile(path.join(__dirname+'/index.html'));
  //__dirname : It will resolve to your project folder.
});
//----------------------------------------------------------------------
//add the router
app.use(express.static(__dirname + '/View'));
//Store all HTML files in view folder.
app.use(express.static(__dirname + '/Script'));
//Store all JS and CSS in Scripts folder.
app.use('/', router);
app.listen(process.env.port || 3000);

并使用 html 和 javascript。

index.html

<html>
    <head>
        <meta charset="utf-8"/>
    </head>
    <link rel="stylesheet" href="./index.css">
    <script type="text" src="./server.js"></script>
    <script src="./index.js"></script>
    <body>
        <h1>Automatico</h1>
        <button onclick="autohabilitar();">Habilitar</button>
        <button onclick="autodeshabilitar();">deshabilitar</button>
        <br>
        <h1>Foco-1</h1>
        <button onclick="f1habilitar();" id="f1h">Habilitar</button>
        <button onclick="f1deshabilitar();"id="f1d">deshabilitar</button>
</body>
</html>

index.js

   document.getElementById("f1h").disabled=true;
   document.getElementById("f1d").disabled=true;
}

function autodeshabilitar(){
    document.getElementById("f1h").disabled=false;
    document.getElementById("f1d").disabled=false;
}

function f1habilitar(){
    document.getElementById("f1h").disabled=true;
    document.getElementById("f1d").disabled=false;
}

function f1deshabilitar(){
    document.getElementById("f1d").disabled=true;
    document.getElementById("f1h").disabled=false;
}

我需要这个功能

function apagarf1(){
  led1.off();
}

位于 server.js 用于点击按钮... 我尝试导出函数,在 html 中导入脚本,在另一个脚本中使用 johnny-5...

我对 Johnny 5 不是很熟悉。但我知道您无法从浏览器访问 node.js 特定内容。

您最好的选择是在您从前端代码调用的 express 中设置一个基本的 api 端点。当该端点被击中时,您可以触发您的 nodejs 函数来关闭 LED。

在您的服务器文件中添加:

app.get('/led-off', (req, res) => {

  apagarf1()

  return res.send('LED off');

});

在您的前端对该端点进行 fetch() 调用,这应该会起作用。