Javascript 如何在回调函数中将ID发送到数据库进行搜索
我在db.js中有一个代码片段,如下所示Javascript 如何在回调函数中将ID发送到数据库进行搜索,javascript,node.js,rest,Javascript,Node.js,Rest,我在db.js中有一个代码片段,如下所示 exports.asyncGetAllData = function (cb) { connection.connect(function(err) { connection.query("SELECT * FROM prices WHERE=" + "'" + ID + "'", function (err, result) { //console.log("info:" + cb
exports.asyncGetAllData = function (cb) {
connection.connect(function(err) {
connection.query("SELECT * FROM prices WHERE=" + "'" + ID + "'", function (err, result) {
//console.log("info:" + cb);
if (err) console.log("Error: " + err);
else
{
cb(result);
}
});
});
};
我想将和ID从app.js传递到db.js中的asyncGetAllData函数中。下面的代码片段位于app.js中
app.get('/test/getPriceTrend/:parameter', function(req, res) {
console.log('SERVER::testGetPriceTrend');
console.log(req.url);
var str=req.url;
db_connection.asyncGetAllData(function(data) {
var obj = str.split("&");
var ID = obj[0].split("/")[3];
console.log(JSON.stringify(data));
res.setHeader('Accept', 'application/json');
res.writeHead(res.statusCode);
//The following piece of code will send information from the database
res.write("hello");
res.end();
});
var str = req.url;
var obj = str.split("&");
var ID = obj[0].split("/")[3];
db_connection.asyncGetAllData(function(data) {
...
}, ID);
}))
在上面提到的代码(app.js)中,我解析了get请求的ID。我想将此ID发送到位于db.js中的asyncGetAllData函数。如何发送ID参数并获取结果
提前感谢,您只需使用附加参数扩展函数即可
exports.asyncGetAllData = function (cb, ID) {
connection.connect(function(err) {
connection.query("SELECT * FROM prices WHERE=" + "'" + ID + "'" ...
然后在app.js中调用函数时传递它
app.get('/test/getPriceTrend/:parameter', function(req, res) {
console.log('SERVER::testGetPriceTrend');
console.log(req.url);
var str=req.url;
db_connection.asyncGetAllData(function(data) {
var obj = str.split("&");
var ID = obj[0].split("/")[3];
console.log(JSON.stringify(data));
res.setHeader('Accept', 'application/json');
res.writeHead(res.statusCode);
//The following piece of code will send information from the database
res.write("hello");
res.end();
});
var str = req.url;
var obj = str.split("&");
var ID = obj[0].split("/")[3];
db_connection.asyncGetAllData(function(data) {
...
}, ID);