我编写了一个查询MySQL数据库的API,并输出访问网址的相应结果。这是代码:
//server.js
var express = require('express'),
mysql = require('mysql'),
app = express(),
connectionpool = mysql.createPool({
host : 'localhost',
user : 'root',
password : 'password',
database : 'database'
});
app.get('/:transcript', function(req,res){
var var1 = req.param('transcript');
exports.var1 = var1;
var queries = require('./queries'),
query1 = queries.query1;
//Connection to MySQL
connectionpool.getConnection(function(err, connection) {
if (err) {res.send({result: 'error connection'})}
connection.query(query1, function(err, rows) {
if (err) {res.send({result: 'error query1'})};
counter = 0; root = {};
rows.forEach(function (row) {
build_actor(row.Transcript_alias, function(exprobject1) {
counter += 1;
//Defining and filling objects
main = {};
main.Official_transcript_name = row.Transcript_name;
main.Expression = exprobject1;
root[row.Transcript_alias] = main;
if (counter == rows.length) {
res.write(JSON.stringify(root, null, '\t'));
res.end();
}
});
});
connection.release();
});
//CallBack
function build_actor(transcript, callback) {
//Other, secondary queries:
var query2 = 'SELECT * FROM expression WHERE transcript_alias = "' + transcript + '";',
connection.query(query2, function(err, rows1) {
if (err) {res.send({result: 'error query2'})}
var exprobject2 = {},
exprobject1 = {};
for (i = 0; i < rows1.length; i++) {
Conditions = rows1[i].conditions;
Tissue = rows1[i].tissue;
FPKM = rows1[i].FPKM;
exprobject2[Tissue] = FPKM;
if (Conditions in exprobject1) {
exprobject1[Conditions].push(exprobject2);
} else {
exprobject1[Conditions] = [];
exprobject1[Conditions].push(exprobject2);
}
}
callback(exprobject1);
});
}
});
});
app.listen(3000);
console.log('Listening on port 3000');
此脚本调用我的查询所需的文件:
//queries.js
var server = require('./server'),
query1 = 'SELECT distinct(transcript_alias)\
FROM transcript_features \
WHERE f.transcript_alias = "' + var1 + '";';
exports.query1 = query1;
我用这种方式转到这个脚本的内容:
http://localhost:3000/AC149829.2_FGT004
http://localhost:3000/AC148152.3_FGT007
当我第一次访问http://localhost:3000/AC149829.2_FGT004
时,API会显示变量AC149829.2_FGT004
的正确结果。但是,将变量更改为AC148152.3_FGT007
时,会继续显示变量AC149829.2_FGT004
的信息。为了查看AC148152.3_FGT007
的结果,我必须删除脚本,再次调用它,并首次访问http://localhost:3000/AC148152.3_FGT007
。总之,结果不会更新。
app.get('/:transcript', function(req,res){
var input = req.param('transcript');
res.send(input);
});
但效果很好......
修改即可。我找到了问题的根源。 query1
总是一样的。该脚本只调用一次:
exports.var1 = var1;
var queries = require('./queries'),
query1 = queries.query1;
有办法克服这个限制吗?
答案 0 :(得分:0)
我找到了解决问题的方法。正如
//server.js
exports.var1 = var1;
var queries = require('./queries'),
query1 = queries.query1;
执行一次并保留在缓存中,我更改了代码而未导出var1
:
//server.js
var queries = require('./queries'),
query1 = queries.query1 + var1;
和
//queries.js
var server = require('./server'),
query1 = 'SELECT distinct(transcript_alias)\
FROM transcript_features \
WHERE f.transcript_alias = ';
exports.query1 = query1;
换句话说,我将查询导入server.js
而没有任何变量。该变量在server.js
分配。