Here is a question about node.js
that I need to answer. Since I am still a beginner in the field, it may actually be quite easy.
Following some documentation that I found online, I have this code (inside a file called index.js):
app.get('/db', function (request, response) {
pg.connect(process.env.DATABASE_URL, function(err, client, done) {
client.query('SELECT * FROM test_table', function(err, result) {
done();
if (err)
{ console.error(err); response.send("Error " + err); }
else {
response.render('pages/db', {results: result.rows} );
}
});
});
});
and I also have this other file called db.ejs:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="container">
<h2>Database Results</h2>
<ul>
<% results.forEach(function(r) { %>
<li><%= r.id %> - <%= r.name %></li>
<% }); %>
</ul>
</div>
</body>
</html>
By some magic between the two I can display the contents of test_table. It works as one would expect.
Now here comes my question:
Along with the query: 'SELECT * FROM test_table' I also want to add a second query: 'SELECT * FROM other_test_table' and I want to be able to display the contents of other_test_table after (or before) that of test_table. How do I need to change the code in both places for that?
You can try:
app.get('/db', function (request, response) {
pg.connect(process.env.DATABASE_URL, function(err, client, done) {
client.query('SELECT * FROM test_table', function(err, result1) {
if (err) {
done();
console.error(err);
response.send("Error: " + err.message);
} else {
client.query('SELECT * FROM other_test_table', function(err, result2) {
done();
if (err) {
console.error(err);
response.send("Error: " + err.message);
} else {
response.render('pages/db', {
results1: result1.rows,
results2: result2.rows
});
}
});
}
});
});
});
and in db.ejs
:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="container">
<h2>Database Results</h2>
<ul>
<% results1.forEach(function(r) { %>
<li><%= r.id %> - <%= r.name %></li>
<% }); %>
</ul>
<ul>
<% results2.forEach(function(r) { %>
<li><%= r.id %> - <%= r.name %></li>
<% }); %>
</ul>
</div>
</body>
</html>
Hope it helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.