gpt4 book ai didi

mysql - 需要路由中的文件才能运行查询

转载 作者:行者123 更新时间:2023-11-30 21:54:28 24 4
gpt4 key购买 nike

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

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();
});

这里的目标是访问/participants 路由,然后运行选择查询并发送查询结果。

最佳答案

require() 不像其他语言中的 source(..)execute 那样工作。其中的代码只在第一次需要时执行一次。然后缓存该模块。

您需要使用 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();
});
});

关于mysql - 需要路由中的文件才能运行查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45846254/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com