Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
143
rated 0 times [  146] [ 3]  / answers: 1 / hits: 27309  / 9 Years ago, sat, february 14, 2015, 12:00:00

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


More From » node.js

 Answers
6

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.


[#67823] Thursday, February 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tayaw

Total Points: 749
Total Questions: 88
Total Answers: 86

Location: Djibouti
Member since Sun, Feb 27, 2022
2 Years ago
tayaw questions
;