I have created one app using node.js and postgresql to display the user city depending upon the requested user id.If i hit this URL in(localhosthost:7070/user/userId/city) in browser means using express get request i'm calling method to get the requested user city from database using the requested user id.I'm getting correct output without any issues.But i'm facing some other issue.
Issue
First while hitting localhost:7070/user/1/city URL in browser means it's giving the output also the result is displaying in my page.But again if i hit localhost:7070/user/2/city URL in browser means i'm not getting any error and any output but my page is always loading.So if i want to do it for other user means again i have restart my node server.Then only it works.Can anyone help me what is the exact issue.
Here i have attached my code...
server.js
var pg = require('pg');
var conString =require('./config');
var client = new pg.Client(conString);
var queryModule=require('./query');
var express=require('express');
var app=express();
app.use(express.static(__dirname + '/public'));
app.listen(7070);
console.log('Server started at port 7070.');
app.get('/user/:id/city',function(req, response){
client.connect(function(err, result){
if(!err){
var userId=req.param('id');
queryModule.findCityByUserId(client,userId,function(err,res){
if(!err){
console.log('done');
response.send('Requested user city is '+res);
return;
}
console.log('Error while finding the city of the user ' + err);
});
} else {
console.log('error while connecting client '+err);
}
});
});
query.js
function Query(){
}
module.exports=Query;
Query.findCityByUserId = function(client, id, cb){
client.query("SELECT city FROM userinfo WHERE id=" + id, function(err,res){
if(err){
return cb(err);
}
client.end();
var row = res.rows['0'];
console.log("row length: " + res.rows.length);
Object.keys(row).forEach(function(key){
cb(null, row['city']);
});
});
};
I just got started with node.
The problem may be that you're not ending your response with res.end();