Can't access postgres database, query doesn't seem to work - node.js

var client = new pg.Client(clientConfig);
var queryConfig = {text: 'SELECT messageID FROM privateMessages WHERE message = $1',
values: ['test']};
var server = http.createServer(function(request, response) {
client.connect();
response.writeHead(200, {'content-type': 'text/html'});
client.query(queryConfig, function(err, result) {
if (err){
console.log("error");
}
response.end('You are visitor number');
});
client.end();
});
server.listen(3001)
The query being made is valid. But the callback function doesn't seem to work. Why isn't the database being accessed? This has been tried with insertions.

Related

Cannot set headers after they are sent to clients in node.js

My code is not working . I am beginner and don't know my problem. Kindly help.I have seen one or two solution on stackoverflow but didnot get .
This is code.
app.post('/post',(request,response)=>{
var description=request.body.description;
var contact_number=request.body.contact_number;
var city=request.body.city;
var budget=request.body.budget;
var category=request.body.optradio;
var query=connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)",[null,description,category,city,contact_number,budget],function(err){
if(err)
console.log(err);
else
response.send("successful");
});
response.redirect('/data');
});
app.get('/data',function(request,response){
connection.query("SELECT * FROM jobs ORDER BY Jobs_id DESC",(err, rows,fields) => {
if(err) {
console.log(err);
}
else {
response.render('feed', {title : 'Jobs Details',
items: rows })
}
});
});
app.listen(3000);
This is the error
pp.post('/post', (request, response) => {
var description = request.body.description;
var contact_number = request.body.contact_number;
var city = request.body.city;
var budget = request.body.budget;
var category = request.body.optradio;
var query = connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)", [null, description, category, city, contact_number, budget],
function (err) {
if (err) {
console.log(err);
} else {
response.redirect('/data');
}
});
});
app.get('/data', function (request, response) {
connection.query("SELECT * FROM jobs ORDER BY Jobs_id DESC", (err, rows, fields) => {
if (err) {
console.log(err);
}
else {
response.render('feed', {
title: 'Jobs Details',
items: rows
})
}
});
});
app.listen(3000);
There can be only one response to single HTTP request. In your code, you are first trying to send response with
response.send("successful");
but this on its own doesn't break the flow of the function which means that if the condition is actually met then this will execute and the execution continues and finds another response, in this case
response.redirect('/data');
and it will try to send another response to the original http request but at this point it is already too late because one response has already been send.
To solve this issue in general, you can place return in front of any line of code that is closing the the connection (response.send, response.redirect, ...). That way, the function's execution is terminated at the first response, whichever it is.
So you could do something like
var query=connection.query("insert into jobs(Jobs_id,Description,Category,City,Contact_number,Budget) values(?,?,?,?,?,?)",[null,description,category,city,contact_number,budget],function(err){
if(err)
console.log(err);
else
return response.send("successful");
});
return response.redirect('/data');
});

Why does my function lose its return value? [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
Good afternoon, I'm now learning nodeJS. Right now I have a problem with a function I devised and I can't seem to find the problem
var http = require('http');
var mysql = require('mysql');
var url = require('url');
http.createServer(function (req, res) {
if (req.url === '/favicon.ico') {
//res.writeHead(200, {'Content-Type': 'image/x-icon'} );
res.end();
//console.log('favicon requested');
return;
}
var con = mysql.createConnection({
host: "localhost",
user: "admin",
password: "admin",
database: "brandibDB"
});
res.writeHead(200, {'Content-Type': 'text/plain'});
var addr = url.parse(req.url, true);
var teste = addr.pathname.split('/');
var tester = getJson(teste,con);
console.log(tester);
//console.log(teste);
//res.write(teste[1] + teste[2]);
res.end();
}).listen(8080);
function getJson(teste,con){
var resultado = "";
con.connect(function(err){
if (err) throw err;
if(teste[1] == 'users'){
if(teste.length!=2){
var str = "SELECT * FROM tblUsers where id ="+ mysql.escape(teste[2]) + "";
con.query(str, function (err, result, fields) {
if (err) throw err;
resultado = JSON.stringify(result);
});
}
else{
var str = "SELECT * FROM tblUsers";
con.query(str, function (err, result, fields) {
if (err) throw err;
resultado = JSON.stringify(result);
});
}
}
});
con.end;
return resultado;
}
console.log('Isto deve ser uma consola');
right now I have data in a db and I'm testing accessing this server with url: "localhost:8080/users/1" or "localhost:8080/users/"
When I run the second link for example, it should go into the function getJson and return the right value(a json with all the user registries) but it just returns empty. I've tried putting console logs inside the function around the lines "resultado = Json..." and it displays the right value. The result is lost afterwards.
Any tips?
It's because your getJson function has returned before the asynchronous callback from the query has completed, therefore resultado is still an empty string.
Instead you could either provide a callback to getJson that gets called when the query returns, or better still, use promises. Something like this:
var tester = getJson(teste, con)
.then(result => {
console.log('the results were:', results)
})
.catch(err => {
console.log('Something went wrong', err);
});
and your function becomes something like:
function getJson(teste, con) {
return new Promise((resolve, reject) => {
con.connect(function (err) {
if (err) throw err;
if (teste[1] == 'users') {
if (teste.length != 2) {
var str = "SELECT * FROM tblUsers where id =" + mysql.escape(teste[2]) + "";
con.query(str, function (err, result, fields) {
if (err) return reject(err);
return resolve(JSON.stringify(result));
});
} else {
var str = "SELECT * FROM tblUsers";
con.query(str, function (err, result, fields) {
if (err) return reject(err);
return resolve(JSON.stringify(result));
});
}
}
});
})
}
I'd also recommend ditching var and using let and const, it's much easier to keep track of your variable scopes that way.

How to send response to front end after execution of mongodb request?

I am creating sign up page. Where, I first check whether user email already present in our mongodb database or not. If it is present then I want to send error message to frontEnd. However, I am failing to do that, I think it might be because of asynchronous behavior of JavaScript.My Code is as following:
var myObj , myJSON
var SignUpUserEmail, SignUpUserPassword, SignUpUserName, SignUpErr
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var q = url.parse(req.url, true).query
SignUpUserEmail = q.SignUpUserEmail
SignUpUserPassword = q.SignUpUserPassword
SignUpUserName = q.SignUpUserName
MongoClient.connect("mongodb://localhost:27017/ABC",function(err,
database) {
if (err) throw err;
var db=database.db('ABC')
let findOneParam = {"UserEmail":SignUpUserEmail}
db.collection('Profiles').findOne(findOneParam, function(err, result) {
if (err) throw err;
if(!result) {
db.collection('Profiles', function(err, collection){
if (err) throw err;
collection.insertOne({"UserId":"ProfileA0001",
"UserEmail":SignUpUserEmail,
"UserPassword":SignUpUserPassword,
"UserName":SignUpUserName,
"IsEmailAuthenticated":"false"
}, function(err, res){
if (err) throw err;
SignUpErr = "document inserted"
console.log("SignUpErr inside:", SignUpErr)
})
})
} else {
SignUpErr = "Email already has been registered."
console.log("SignUpErr inside:", SignUpErr)
}
})
})
console.log("SignUpErr outside:", SignUpErr)
myObj = {"SignUpErr":SignUpErr};
myJSON = JSON.stringify(myObj);
res.end(myJSON);
}).listen(9000);
Note: "SignUpErr inside:" giving correct result. however, "SignUpErr outside:" shows it as undefined.
Note: "SignUpErr inside:" giving correct result. however, "SignUpErr outside:" shows it as undefined.
This is because of the asynchronous nature of the nodejs. SignUpErr will be undefined until the time it is initialized within the db.collection('Profiles',function(){}) call.
So, to fix this, you need to send response within db.collection('Profiles',function(){}). that's, after the initilization.
Making those changes to your code,
'use strict';
const http = require('http');
http.createServer(function (req, res) {
res.statusCode = 200; // Setting the status code
res.setHeader('Content-Type', 'text/plain'); // Setting the content-type for response
let {SignUpUserEmail, SignUpUserPassword, SignUpUserName} = url.parse(req.url, true).query;
MongoClient.connect("mongodb://localhost:27017/ABC", function (err, database) {
if (err) {
throw err;
}
let db = database.db('ABC');
db.collection('Profiles').findOne({
UserEmail: SignUpUserEmail
}, function (err, result) {
if (err) {
throw err
}
if (result) {
let msg = "Email already has been registered.";
console.log("SignUpErr inside:", msg);
return res.end(JSON.stringify({
SignUpErr: "document inserted"
}));
}
db.collection('Profiles', function (err, collection) {
if (err) throw err;
collection.insertOne({
"UserId": "ProfileA0001",
"UserEmail": SignUpUserEmail,
"UserPassword": SignUpUserPassword,
"UserName": SignUpUserName,
"IsEmailAuthenticated": "false"
}, function (err, dbresult) {
if (err) {
throw err;
}
let msg = "document inserted";
console.log("SignUpErr inside:", msg);
return res.end(JSON.stringify({
SignUpErr: "document inserted"
}));
})
});
});
});
}).listen(9000);
I usually use express as my web framework which comes with res.send() method, where you can send your response . I usually build a JSON response, and send it as res.send(JSON.stringify(data)); There is also res.JSON(data).
If you wish to use HTTP module , then you can use res.end() method.
Details are provided here . Hope this helps.

Is it possible to query multiple keys in firebase (node.js) at once?

Currently I am doing a forEach loop to populate the array based on user's favorites:
usersref.child(formData.openid + '/favorites').once('value', function(snapshot){
var favlist = [];
snapshot.forEach(function(fav){
fav = fav.key();
ref.child(fav).once('value',function(snapshot){
favlist.push(snapshot.val());
});
});
response.writeHead(200, {'Content-Type': 'application/javascript'});
response.write(favlist);
response.end();
});
usersref is a the database for the user, ref is the database for the items. formData.openid is user's unique id.
Since the two lists are disjunct, you'll need a separate read for each item. But to ensure all reads are done before sending the response to the client, you can use promises:
usersref.child(formData.openid + '/favorites').once('value', function(snapshot){
var promises = [];
snapshot.forEach(function(fav){
promises.push(ref.child(fav.key()).once('value'));
});
Promise.all(promises).then(function(snapshots) {
var favlist = snapshots.map(function(snapshot) { return snapshot.val(); });
response.writeHead(200, {'Content-Type': 'application/javascript'});
response.write(JSON.stringify(favlist));
response.end();
}).catch(function(error) {
response.status(500).send(error);
});
});

rest api using express.js and PostgreSQL

I have a script that has rest apis that gets data from a postgresql database and returns it back to the client. At the start, the script only uses the about 7mb of memory and the response time when making queries is very fast. However, as time passes by(about 1 day), the memory used by the script balloons to 170mb. And now, the queries takes more than 1 minute to respond. But when I restart the script, it is now again fast on its response. I am clueless as to why this happens. Can anybody shed light on this? Here is a portion of what my script looks like:
var port = process.env.PORT || 8000;
var router = express.Router();
router.get('/:id/from/:prevdate', function (req, res) {
var results = [];
var id = req.params.id;
var prevdate = req.params.prevdate;
pg.connect(connectionString, function (err, client, done) {
var query = client.query("some sql statement here", [id, prevdate]);
query.on('row', function (row) {
results.push(row);
});
query.on('end', function () {
client.end();
return res.json(results);
});
if (err) {
console.log(err);
}
});
});
router.get('/:id/getdata', function (req, res) {
var results = [];
var id = req.params.id;
pg.connect(connectionString, function (err, client, done) {
var query = client.query("some sql statement here", [id]);
query.on('row', function (row) {
results.push(row);
});
query.on('end', function () {
client.end();
return res.json(results);
});
if (err) {
console.log(err);
}
});
});
app.use('/restapitest', router);
app.listen(port);
console.log('Webservice started using port: ' + port);
You are mixing connection pooling (which uses done()) with creating single connections (which uses client.end()).
Try this:
query.on('end', function() {
done();
return res.json(results);
});
Also, since you are storing all results in memory anyway, there's no need to use events. So with proper error and connection handling, you could use this:
pg.connect(connectionString, function (err, client, done) {
var sendError = function(err) {
console.log(err);
return res.sendStatus(500);
};
if (err) return sendError(err);
client.query("some sql statement here", [id, prevdate], function(err, results) {
// Done with the client.
done();
// Handle any errors.
if (err) return sendError(err);
// Return result
return res.json(results);
});
});

Resources