简体   繁体   中英

How to pass data from express to ejs

I have server.js file with query:

app.get('/tasks', function(req, res) {
  pool.query('SELECT * FROM tasks ORDER BY task_id ASC', (error, results) => {
    if (error) {
      throw error
    }
    console.log(results.rows[0]);
    res.render('pages/tasks', {data: results.rows});
  })
});

And in EJS file, where I would like to display data:

<main>
  <div>
    <h1>res: <% data %></h1>
  </div>
</main>

Unfortunately in EJS file variable data is empty while results.rows[0] in server.js file displays correct value.

How can I pass data from server.js to EJS file?

you are missing a "="

<%= data %>

and you have to iterate through data as its not a single data and if you wanna print a single data then pass only one data

res.render('pages/tasks', {data: results.rows[0]});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM