簡體   English   中英

如何使用nodejs的功能在html中的按鈕中使用joohny 5?

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

我使用 nodejs 和 express 創建了一個服務器

服務器.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);

並在 javascript 中使用 html。

索引.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>

索引.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-five...

我對 Johnny 5 不是很熟悉。但我知道你不能從瀏覽器訪問 node.js 特定的東西。

您最好的選擇是在您從前端代碼調用的 express 中設置一個基本的 api 端點。 當該端點被擊中時,您可以觸發您的 nodejs 函數來關閉 LED。

在您的服務器文件中添加以下內容:

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

  apagarf1()

  return res.send('LED off');

});

在您的前端對該端點進行 fetch() 調用,這應該可以工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM