我有我的代码 ::
var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var mysql=require('mysql');
var async=require('async');
var app=express();
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'ImagePostingDB'
});
connection.connect();
app.set('port',process.env.PORT||7002);
app.use('/Details',express.static(__dirname+'/public/images'));
app.use(express.bodyParser());
app.get('/DescriptionSortedPrice/',function(request,response){
var name_of_restaurants;
async.series( [
// Get the first table contents
function ( callback ) {
connection.query('SELECT * FROM ImagePostingtable ORDER BY Sl_no', function(err, rows, fields)
{
console.log('Connection result error '+err);
name_of_restaurants = rows;
callback();
});
}
// Send the response
], function ( error, results ) {
response.json({
'restaurants' : name_of_restaurants
});
});
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
当我尝试使用postman ::我没有JSON响应 ::
或
var express=require('express');
var fs=require('fs');
var http=require('http');
var crypto=require('crypto');
var mysql=require('mysql');
var async=require('async');
var app=express();
var connection=mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'ImagePostingDB'
});
connection.connect(function(err) { if ( !err ) { console.log("Connected to MySQL"); } else if ( err ) { console.log(err); } });
app.set('port',process.env.PORT||7002);
app.use('/Details',express.static(__dirname+'/public/images'));
app.use(express.bodyParser());
app.get('/DescriptionSortedPrice/',function(request,response){
connection.query('SELECT * FROM ImagePostingtable ORDER BY Sl_no', function(err, rows, fields) {
if (err) {
return response.send(500, err.message);
}
response.json({
'restaurants' : rows
});
});
});
http.createServer(app).listen(app.get('port'),function(){
console.log('Express server listening on port'+app.get('port'));
});
我的命令提示符中有一个快照,例如::
答案 0 :(得分:1)
首先:您可以确认启动请求时服务器没有崩溃吗?响应代码0通常表示连接被切断(或者根本没有响应)。
async.series
应该用于串行调用多个异步函数:如果只调用一个函数,则无需使用它。
async.series
中的回调遵循Node.js的回调样式,这意味着他们将错误(或null
)作为第一个参数,然后是函数的结果。但你不发送任何论据:callback()
。但是,您的代码仍然有效,因为您使用了在异步函数中覆盖的局部变量name_of_restaurants
。要小心,因为这不是你应该如何使用这种模式。这是一个更优雅的解决方案:
app.get('/DescriptionSortedPrice/',function(request,response){
connection.query('SELECT * FROM ImagePostingtable ORDER BY Sl_no', function(err, rows, fields) {
if (err) {
console.log('Encountered an error:', err.message);
return response.send(500, err.message);
}
console.log('Found results:', rows);
response.json({
'restaurants' : rows
});
});
});