从浏览器(使用Express)在Node js中调用方法 [英] Calling method in Node js from browser (Using Express)

查看:359
本文介绍了从浏览器(使用Express)在Node js中调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在app.js中定义了这三个路由

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;

因此,当我转到/LEDon页面时,该方法将运行,并且一切正常.是否可以在不使用get请求的情况下运行方法?我的主要目标是单击超链接,然后运行该方法.

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

推荐答案

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

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

类似的stackoverflow问题应该帮助您.

我做了一个简单的示例,涉及多个文件:

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>

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

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.

这篇关于从浏览器(使用Express)在Node js中调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆