0

Here is my get request made to a mysql table

app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
    if(err){console.log(err);}
    else{
        console.log(results);

    }
});
res.render('index');

});

As it stands, this function allows me to grab the information I want from the table and I can read the results via console.log. However, I'm unable to access results on my index.ejs page.

How do I access results(which is an object that contains the stuff I want) in my index.ejs file? Whenever I try to access results, it says that results in undefined. How do I make sure that the object that is created as a result of the call to the table is able to be used/accessed on a different page. For the time being, I would just like to create a simple table that has the keys in one column and the values in a second column.

VK1
  • 1,676
  • 4
  • 28
  • 51

1 Answers1

0

You need to modify your code as below. The reason is db.query is an async operation and you are trying to render before the async request completed. Also, to be able to reach the result at your template engine, you need to pass the results to the render. (index.ejs)

app.get('/', (req, res) => {
let sql = 'SELECT * from emarttesttable WHERE id = 229';
let query = db.query(sql, (err, results) => {
    if(err){console.log(err);}
    else{
        res.render('index', results);
        console.log(results);

    }
});
Volem
  • 616
  • 3
  • 15
  • Thank you for responding to my question. I rewrote the function so that the render comes direction after the else statement(as you did). However, I'm still unable to display results in my index.ejs file. What would be the simplest way to display results within in a div?
    <% results %>
    ?
    – VK1 Jul 26 '17 at 16:04
  • quick update: using res.render('index', {results: results}); and then using

    <%- JSON.stringify(results) %> in my ejs file, I was able to view the results. Not sure how I'm going to parse the results so I can create a table with 2 columns

    – VK1 Jul 26 '17 at 16:16
  • Without {results: results} the answer you supplied doesn't completely work. If you can provide a way to display results with ejs file..I'd love to give you credit. I really appreciate you pointing out needed to move the res.render function. – VK1 Jul 27 '17 at 05:07