我有一个来自 Express 的工作代码,它将 JSON 响应从服务器返回到客户端
这里
- 当我使用时,
http:://myserverip/
我从 Table1 中得到一个 JSON - 当我使用时,
Http:://myserverip/table2
我从 Table2 中得到一个 JSON
因此,据我所知,我需要发出 2 个单独的请求才能从两个单独的表中获取 JSON 但是有没有办法在一个 JSON 响应中一次从两个表中获取数据
var express = require('express')
, http = require('http')
, mysql = require('mysql'); // <---- HERE
var app = express();
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: "root",
database: 'DB'
});
connection.connect(); // <---- AND HERE
// all environments
app.set('port', process.env.PORT || 7002);
app.get('/',function(request,response){
connection.query('SELECT * FROM table1', function(err, rows, fields)
{
console.log('Connection result error '+err);
console.log('no of records is '+rows.length);
response.writeHead(200, { 'Content-Type': 'application/json'});
response.end(JSON.stringify(rows));
});
} );
app.get('/table2',function(request,response){
connection.query('SELECT * FROM table2', function(err, rows, fields)
{
console.log('Connection result error '+err);
console.log('no of records is '+rows.length);
response.writeHead(200, { 'Content-Type': 'application/json'});
response.end(JSON.stringify(rows));
});
} );
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
谢谢