Javascript 从浏览器调用 Node js 中的方法(使用 Express)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28516951/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Calling method in Node js from browser (Using Express)
提问by user2255273
I defined these three routes in app.js
我在 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..
因此,当我转到 /LEDon 页面时,该方法会运行并且一切正常。是否可以在不使用 get 请求的情况下运行方法?我的主要目标是只需单击一个超链接,然后运行该方法..
回答by Keith Yong
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 POSTAFAIK is Socket.io
本质上,您是在要求客户端脚本直接调用 Node 服务器脚本上的函数。除了 Ajax POSTAFAIK之外,唯一的其他选择是Socket.io
This similar stackoverflow questionshould help you out.
这个类似的 stackoverflow 问题应该可以帮到你。
edit: I made a simple example spanning multiple files:
编辑:我做了一个跨越多个文件的简单例子:
/test/app.js:
/测试/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
/测试/clientside.js
$('#ledon-button').click(function() {
$.ajax({
type: 'POST',
url: 'http://localhost:1337/LEDon'
});
});
/test/view.html
/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.jsin terminal, and open view.htmlon your browser. Try pressing the button and check out your terminal. Hope this helps.
运行它:node app.js在终端中,并view.html在浏览器上打开。尝试按下按钮并检查您的终端。希望这可以帮助。
回答by siavolt
For resolve your problem you can use ajaxrequest, for example:
为了解决您的问题,您可以使用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>

