从浏览器调用 Node js 中的方法(使用 Express)

Calling method in Node js from browser (Using Express)

我在app.js

中定义了这三个路由
app.use('/', require('./routes/index'));
app.use('/LEDon', require('./routes/LEDon'));
app.use('/LEDoff', require('./routes/LEDoff'));

在我的路由文件中有以下内容:

var express = require('express');
var router = express.Router();
var Gpio = require('onoff').Gpio,
    led = new Gpio(17, 'out');

router.get('/', function(req, res, next) {
  led.writeSync(1);
});

module.exports = router;

因此,当我转到 /LEDon 页面时,方法 运行s 一切正常。是否可以 运行 一种方法而不使用 get 请求?我的主要目标是只需单击一个超链接,然后 运行 就是方法..

本质上,您是在要求客户端脚本直接调用 Node 服务器脚本上的函数。除了 Ajax POST AFAIK 之外,唯一的选择是 Socket.io

这个 similar Whosebug question 应该能帮到你。


编辑:我做了一个跨越多个文件的简单示例:

/test/app.js:

var express = require('express');
var app = express();

app.post('/LEDon', function(req, res) {
    console.log('LEDon button pressed!');
    // Run your LED toggling code here
});

app.listen(1337);

/test/clientside.js

$('#ledon-button').click(function() {
    $.ajax({
        type: 'POST',
        url: 'http://localhost:1337/LEDon'
    });
});

/test/view.html

<!DOCTYPE html>
<head>
</head>

<body>
    <button id='ledon-button'>LED on</button>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src='clientside.js'></script>
</body>

到运行它: node app.js 在终端中,然后在浏览器中打开view.html。尝试按下按钮并检查您的终端。希望这有帮助。

为了解决您的问题,您可以使用ajax请求,例如:

<body>
    <a onClick=LEDon>LED On</a>
    <a onClick=LEDoff>LED Off</a>

    <script>
    function LEDon(){
       $.ajax({
          url: "http://yourDomain.com/LEDon"
       });
    }

    function LEDoff(){
       $.ajax({
          url: "http://yourDomain.com/LEDoff"
       });
    } 

    </script>
<body>

老问题 - 我知道。但随着时间的推移,新的方式出现了。

我可以建议尝试 api-mount。它基本上允许调用 API 作为简单的函数,而不必考虑 AJAX 请求、获取、表达等。基本上在服务器中你做:

const ApiMount = apiMountFactory()
ApiMount.exposeApi(api)

"api" 基本上是 methods/functions 的对象,您愿意从 Web 应用程序中调用它。

然后在 Web 应用程序上执行此操作:

const api = mountApi({baseUrl: 'http://your-server.com:3000'})

完成后,您可以像这样调用您的 API:

const result = await api.yourApiMethod()

试试吧。希望对你有帮助。