我正在尝试在nodejs中编写一个带有两个查询的api,从查询中获取的数据应该合并,并且应该从服务器发送一个json响应。我尝试了以下方式,但不知怎的,我得到了空值。
app.get('/api/task_details',function(req,res,err){
var sql = "select * from users inner join user_level_task on users.user_id=user_level_task.user_id inner join tasks on tasks.task_id = user_level_task.task_id where task_name = 'game'";
var sql2="select * from tasks where task_name='game'";
var res1 = '',res2='';
db.select(sql,function(err,data){
var res1 =data;
})
db.select(sql2,function(err,data){
var res2 = data;
})
res.end(JSON.stringify(res1+res2));
})
答案 0 :(得分:1)
您的代码应该是这样的。
app.get('/api/task_details',function(req,res,err){
var sql = "select * from users inner join user_level_task on users.user_id=user_level_task.user_id inner join tasks on tasks.task_id = user_level_task.task_id where task_name = 'game'";
var sql2="select * from tasks where task_name='game'";
var res1 = {}
db.select(sql,function(err,data1){
db.select(sql2,function(err,data2){
res1.data1= data1;
res1.data2=data2;
res.end(JSON.stringify(res1));
})
})
})
答案 1 :(得分:0)
试试这段代码
const mysql = require('mysql');
const express = require('express');
const app = express();
var async = require('async');
const connection = mysql.createConnection({
host: 'localhost',
user: 'xxxx',
password: 'xxxx',
database: 'Name of the DataBase'
});
connection.connect();
app.get('/api/task_details', (req, res) => {
async.parallel([
function (callback)
{
setTimeout(function(){
connection.query(SELECT * FROM users inner join user_level_task on users.user_id=user_level_task.user_id inner join tasks on tasks.task_id = user_level_task.task_id where task_name = 'game', (error, data1) => {
if(error) => {
console.log(error)
}
callback(null,data1);
});
},200);
}
function (callback)
{
setTimeout(function(){
connection.query(SELECT * FROM tasks where task_name='game',(error, data2) => {
if(error) => {
console.log(error)
}
callback(null,data2);
});
},100);
}
],
function(err,results){
res.end(JSON.stringify(results));
});
});
希望这会对你有所帮助