I am having problems rendering multiple data query to page.I have done a lot of research but getting an error like Failed to look up view my code is following:
app.get('/xem', function(req,res){
pool.query("SELECT * FROM phim WHERE slider = '1' ORDER BY id DESC Limit 9", function (error, result, client){
if (!!error){
console.log('Error query');
} else {
res.render('xem', {slider:result});
}
});
pool.query("SELECT * FROM phim WHERE new = '1'", function (error, result, client){
if (!!error){
console.log('Error query');
} else {
res.render('xem', {new:result});
}
});
});
When run it code i give error:
82| <!-- END HEAD -->
83| <h1> ok </h1>
>> 84| <%= new %>
85|
new is not defined
How to fix it?
There are two issues with your approach:
res.render() ends the http request, therefore it will fail when called more than once.
You are executing two asynchronous functions and you don't take care of the order of execution
Try this:
var async = require('async');
app.get('/xem', function(req,res){
var final = {};
async.series({
slider: function(cb) {
pool.query("SELECT * FROM phim WHERE slider = '1' ORDER BY id DESC Limit 9", function (error, result, client){
cb(error, result);
})
},
new: function(cb){
pool.query("SELECT * FROM phim WHERE new = '1'", function (error, result, client){
cb(error, result)
})
}
}, function(error, results) {
if (!error) {
res.render('xem', results);
}
});
});
I don't know if your pool uses promises, so just in case this code uses async approach
The code which you have written is not correct for both queries.
You will get always first query result in response
and in first query result you are sending slider as key and expecting name in response
res.render('xem', {slider:result});
change it with
res.render('xem', {new:result});
Since you are giving name key is in second query result which is not reachable in your case
Thank you everyone. I had it working, sample code:
app.get('/xem', function(req,res){
pool.query("SELECT * FROM phim WHERE slider = '1' ORDER BY id DESC Limit 9", function (error, result, client){
var result1 = result;
link('https://drive.google.com/file/d/0BxG6kVC7OXgrQ1V6bDVsVmJMZFU/view?usp=sharing', function(data){
var dataxem = data;
pool.query("SELECT * FROM user", function (error, result, client){
var user = result;
res.render('xem', {slider:result1, link:data, user:user});
});
});
});
})
app.use('/', (req,res) => {
connection.query('select * from users', function(err, rows, fields){
if(err) return;
console.log(rows[0]);
res.send(rows);
});
});
Related
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');
});
I am getting result from query and storing it in a variable which i will send through render but the problem it is giving error variable is not defined. Please help me out. Do correct the code if possible please.
router.get('/create',(req,res)=>{
connection.query('SELECT * FROM purchases',function(error,results,fields){
var voucher = 'PH-'+results.length+1;
connection.query('SELECT * FROM vendors where wid=?',[req.session.w_id],function(err,res,f){
var vendors=res;
connection.query('SELECT * FROM products where wid=?',[req.session.w_id],function(er,r,fi){
var products=r;
})
})
});
res.render('purchase_create',{voucher:voucher,vendors:vendors,products:products});
});
Error is: voucher is not defined
voucher is only available inside the callback function you're passing to connection.query, same thing with the vendors and products. You'll have to move the res.render call into the inner-most function to make this work:
router.get('/create', (req, res) => {
connection.query('SELECT * FROM purchases', function (error, results, fields) {
var voucher = 'PH-' + results.length + 1;
connection.query('SELECT * FROM vendors where wid=?', [req.session.w_id], function (err, res, f) {
var vendors = res;
connection.query('SELECT * FROM products where wid=?', [req.session.w_id], function (er, r, fi) {
var products = r;
res.render('purchase_create', { voucher: voucher, vendors: vendors, products: products });
});
});
});
});
The ‘query’ method of the connection object requires a callback function which will be executed whenever either one of the three events fires – error, fields, results, here denoted by the parameters err, fields and rows respectively.
router.get('/create', (req, res) => {
connection.query('SELECT * FROM purchases', function (error, results, fields)
{
if (error) throw error;
var voucher = 'PH-' + results.length + 1;
connection.query('SELECT * FROM vendors where wid=?', [req.session.w_id], function (err, res, f)
{
if (err) throw err;
var vendors = res;
connection.query('SELECT * FROM products where wid=?', [req.session.w_id], function (er, r, fi)
{
if (er) throw er;
var products = r;
res.render('purchase_create', { voucher: voucher, vendors: vendors, products: products });
});
});
});
});
I'm currently working on a route the returns an array which contains the results from two separate calls to the database. Individually the functions I call in the model functions work as intended. However, when I attempt to combine them by calling the second function within the callback of the first I receive an error that the second function "is not a function". Here is the code in my list route. Note util and errorhandler are files I've created to help with the return format and shouldn't be effecting this error. Any help solving this would be appreciated, Thank you!
route/list
router.route("/list/:id").get(function(req, res) {
list.getListMovie(req.params.id, function(err, list) {
if (err) {
res.json(errorHandler.handleDatabaseErrors(err));
return;
}
var response = [];
response["movies"] = list;
console.log(response)
list.getListTV(req.params.id, function(err, list1) {
if (err) {
res.json(errorHandler.handleDatabaseErrors(err));
return;
}
response["tv"] = JSON.parse(list1);
console.log(response)
res.json(utils.returnFormatForDB(response));
});
});
});
the function definitions within models/list
exports.getListTV = function(userid, done) {
db.get().query('SELECT `idmedia`, `rating`, `title`, `poster_path` FROM
`list` JOIN `tv` ON list.idmedia = tv.tv_id WHERE list.idusers = ?', userid,
function(err, rows) {
if (err) return done(err);
done(null, rows);
});
}
exports.getListMovie = function(userid, done) {
db.get().query('SELECT `idmedia`, `rating`, `title`, `poster_path` FROM
`list` JOIN `movies` ON list.idmedia = movies.movie_id WHERE list.idusers =
?', userid, function(err, rows) {
if (err) return done(err);
done(null, rows);
});
}
EDIT:: I'm not sure of the proper way to mark a question as answered but by fixing the list override and making response an object I was able to get my code to work. Thanks for the help!
You are overwriting the list variable. Try
list.getListMovie(req.params.id, function(err, movieList) {
if (err) {
res.json(errorHandler.handleDatabaseErrors(err));
return;
}
var response = {};
response["movies"] = movieList;
console.log(response)
list.getListTV(req.params.id, function(err, tvList) {
if (err) {
res.json(errorHandler.handleDatabaseErrors(err));
return;
}
response["tv"] = JSON.parse(tvList);
console.log(response)
res.json(utils.returnFormatForDB(response));
});
});
Also, I'm pretty sure you want the response variable to be an object, not an array.
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);
});
});
I am trying to accomplish the following (should be quite basic and I must be missing something trivial):
Call a function with string that has a select statement
Wait until the DB call completes and the rows (or json equivalent) is returned
Populate http object to return back
Here is code:
util.js
exports.execute = function( query){
if (connection) {
connection.query(query, function(err, rows, fields) {
if (err) throw err;
console.log("from Util - " + JSON.stringify(rows));
return JSON.stringify(rows);
});
}
};
repo.js
var q = "select * from xxx";
var response;
util.execute(q, function (err, r){
if (err){
throw err;
console.log(err);
}
else {
console.log(r);
res.contentType('application/json');
res.write(r);
res.end();
}
});
My problem is while the code within util.js is called and I can see the json in console, it never comes back to the anonymous call back function in the repo.js.
What am I doing wrong here ?
Update
Thanks Ben
I also found the solution in same line ... here is new code:
repo.js:
var send_data = function (req, res, r){
res.contentType('application/json');
res.write(r);
res.end();
}
exports.all = function(req, res){
var q = "select * from XXX";
var response;
util.execute(req, res,q, send_data);
};
util.js:
exports.execute = function(req, res, query, callback){
if (connection) {
connection.query(query, function(err, rows, fields) {
if (err) throw err;
callback(req, res, JSON.stringify(rows)) ;
});
}
};
util.execute only accepts one parameter in your code. It needs to accept a second callback parameter in order to use it the way you do. (Callbacks aren't magic, they're just function calls)
Something like:
exports.execute = function(query,callback){
if (connection) {
connection.query(query, function(err, rows, fields) {
if (err) throw err;
console.log("from Util - " + JSON.stringify(rows));
callback(null,JSON.stringify(rows));
});
}
};
If you'd like it to behave consistently and accept an error parameter, you might want fill that in:
exports.execute = function(query,callback){
if (connection) {
connection.query(query, function(err, rows, fields) {
callback(err,null);
console.log("from Util - " + JSON.stringify(rows));
callback(null,JSON.stringify(rows));
});
}
};