Javascript Node.js:通过前端执行服务器脚本
我想在我的网站上执行一些特定的Javascript Node.js:通过前端执行服务器脚本,javascript,jquery,html,node.js,express,Javascript,Jquery,Html,Node.js,Express,我想在我的网站上执行一些特定的节点JS文件,其中包含一个点击事件 我正在使用express运行我的服务器和网站。我认为正确的方法是使用jQuery和一些GET请求。如果我在控制台中使用“node examplefile.JS” 该文件如下所示: var MapboxClient = require('mapbox'); var client = new MapboxClient(''); client.listStyles(function (err, styles) { console
节点
JS
文件,其中包含一个点击事件
我正在使用express
运行我的服务器和网站。我认为正确的方法是使用jQuery
和一些GET
请求。如果我在控制台中使用“node examplefile.JS”
该文件如下所示:
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
console.log(styles);
});
我想在每次单击事件发生时执行此文件
我是否必须将其作为模块导出到我的app.js
?这是我想要做的,但我在实现中失败了
关于如何实现这一点,有什么建议或简单的例子吗?最好创建一个新模块,然后从express app调用它
创建新模块(getStyles.js):
在express应用程序中使用它:
...
var getStyles = new MapboxClient('path/to/getStyles');
app.get( '/your/route/here', function (req, res, next) {
getStyles( function (err, styles) {
if (err) return next(err);
res.render('view', styles)
});
});
...
但是,如果要从express执行命令行,请使用函数,下面是一个示例:
...
const exec = require('child_process').exec;
app.get( '/on/click/buton/route', function (req, res, next) {
exec('/usr/bin/node file/path/.js', function (err, stdout, stderr) {
if (err) {
return next(err);
}
// send result to the view
res.render('veiw', { res: stdout});
});
});
...
1.在函数中编写examplefile.js
function a(){
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
console.log(styles);
});
2.在app.js中包含examplefile.js
<script src="examplefile.js" type="text/javascript"></script>
3.然后从app.js文件中通过onclick()事件调用()
<input type="button" onclick="javascript: a();" value="button"/>
这就是我所理解的,你正试图这么做
<input type="button" onclick="javascript: a();" value="button"/>