Calling method in Node js from browser (Using Express)

 ̄綄美尐妖づ 提交于 2020-05-09 18:06:07

问题


I defined these three routes in app.js

app.use('/', require('./routes/index'));
app.use('/LEDon', require('./routes/LEDon'));
app.use('/LEDoff', require('./routes/LEDoff'));

In my route file I have the following:

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;

So when I go to the /LEDon page the method runs and everything works. Is it possible though to run a method without using a get request? My main goal is to just click a hyperlink which then runs the method..


回答1:


Essentially you are asking your client side script to directly call a function on your Node server script. The only other choice other than an Ajax POST AFAIK is Socket.io

This similar stackoverflow question should help you out.


edit: I made a simple example spanning multiple files:

/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>

To run it: node app.js in terminal, and open view.html on your browser. Try pressing the button and check out your terminal. Hope this helps.




回答2:


For resolve your problem you can use ajax request, for example:

<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>


来源:https://stackoverflow.com/questions/28516951/calling-method-in-node-js-from-browser-using-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!