要求path中的文件运行查询

我试图设置我的路线,然后包括一个“内容”文件,将运行查询

app.get('/participants', function(req, res, next) { var participants = require('./content/participants'); }); 

然后参与者文件:

 const db = database.connect('olmsdb.1sserver.com', 'campyio'); db.raw('SELECT * FROM participants').then(function(results) { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(results)); return results; db.destroy(); }); 

这里的目标是击中/参与者路线,然后运行select查询并发送查询结果。

require()不能像source(..)那样工作,或者用其他语言来execute 。 其中的代码只在第一次需要时才执行一次。 然后模块被caching。

您需要使用module.exports等函数和类在模块文件中module.exports

去做这个:

participants.js

 const db = database.connect('olmsdb.1sserver.com', 'campyio'); exports.getParticipants = function() { return db.raw('SELECT * FROM participants'); } 

app.js

 var participants = require('./content/participants'); app.get('/participants', function(req, res, next) { participants.getParticipants().then(function(results) { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify(results)); next(); }); }); 

您需要将该代码放在导出的函数中,以便每次请求时都可以使用请求和响应来调用它。

这意味着在你的路由处理程序中require()