![](/img/trans.png)
[英]Linking back-end (MongoDB via Mongoose, on Express server in Node.js) to front-end (Bootstrap or Foundation) in a reactive way?
[英]Node.js: Execute server scripts via front-end
我想在我的網站on-click
事件執行一些特定的node
JS
文件。
我正在使用express
來運行我的服務器和網站。 我認為正確的方法是使用jQuery
和一些GET
請求。 JS文件正在工作,如果我只是在控制台中使用"node examplefile.js"
調用它們
該文件如下所示:
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
client.listStyles(function (err, styles) {
console.log(styles);
});
我希望每次發生on-click
事件時都執行此文件。
我是否必須將此模塊作為模塊導出到我的app.js
? 這就是我想要做的,但我在實施中失敗了。
有關如何實現這一點的任何建議或簡單示例?
創建一個新模塊然后從Express應用程序調用它會好得多
創建新模塊(getStyles.js):
var MapboxClient = require('mapbox');
var client = new MapboxClient('');
module.exports = function (done) {
client.listStyles(function (err, styles) {
if (err) {
return done(err);
}
done(null, styles);
});
}
在express app中使用它:
...
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執行命令行,那么使用exec函數,這里有一個例子:
...
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"/>
這就是我所理解的,你正在努力做到的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.