简体   繁体   中英

How to can I share all of mysql rows in Node.js? (handlebars)

I used this commans for sharing the first row (jack). node:

const express = require("express");
const app = express();
app.set("view engine","hbs")
const mysql = require("mysql")
const db = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "",
    database: "stack",
})

app.get("/", (req, res)=>{
    
    db.query("SELECT * FROM names", (err, result)=>{
    
        res.render("home", {name: result[0].name})
        
    })
    
})

app.listen("1999")

and hbs file:

<html>
<head>
</head>
<body>
<b> {{name}} </b>
</body>
</html>

but but this project only shares first row of mysql result (jack)... how to can I share all of mysql results?

https://handlebarsjs.com/guide/builtin-helpers.html#each

app.get("/", (req, res)=>{  
    db.query("SELECT * FROM names", (err, result)=>{
        res.render("home", {names: result }) // pass all the results     
    });
});

hbs file:

loop over all names using {{#each names }}

<html>
<head>
</head>
<body>
  {{#each names }}
   <h3> {{ this.name }} </h3>
 {{/each}}
</body>
</html>

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