【问题标题】:How to create html table dynamically from database with node.js and express?如何使用node.js从数据库动态创建html表并表达?
【发布时间】:2018-03-19 19:42:11
【问题描述】:

我是 node.js 的新手,我想用 express 和 postgresql 创建一个简单的电话簿应用程序。我想要两个页面,一个用于添加新联系人,另一个用于在 html 表中显示联系人,并能够更新或删除行。到目前为止,我已经实现了插入,但我不知道如何从数据库动态创建“contacts.html”页面。提前谢谢!

index.html

<header>
    <ul>
        <li><h2>Phonebook</h2></li>
        <li><a href="index.html" id="index">New Contact</a></li>
        <li><a href="contacts.html" id="contacts">Contacts</a></li>
    </ul>
</header>

<section>
    <form action="insertContact">
        <p>Full Name</p>
        <input type="text" name="fullname" required>

        <p>Phone</p>
        <input type="text" name="phone1" required>

        <p>Mobile</p>
        <input type="text" name="phone2">

        <p>Address</p>
        <input type="text" name="address" required> <br><br>

        <input type="submit" name="submitBtn" id="submitBtn" value="Submit">
    </form>
</section>

server.js

var express = require('express');
var path = require('path');
var db = require('pg');
var http = require('http');

var app = express();

app.use(express.static(path.join(__dirname,'/')));

var dbConnection = "postgres://postgres:root@localhost:5432/Phonebook";

app.get('/insertContact',function(req,res){
    var dbClient = new db.Client(dbConnection);

    dbClient.connect(function(err){
        if(err)
            throw err;

        var query = "insert into Contacts (fullname,phone,mobile,address) values ($1,$2,$3,$4)";
        var fullname = req.query.fullname;
        var phone = req.query.phone1;
        var mobile = req.query.phone2;
        var address = req.query.address;

        var contact = [fullname , phone , mobile , address];

        dbClient.query(query , contact , function(err){
            if(err)
                throw err;
            else {
                console.log('Success!') ;
                res.redirect('/');      
                res.end();
            }               
        });
    });
});

app.get('????',function(req,res) {
    var dbClient = new db.Client(dbConnection);

    dbClient.connect(function(err){
        if(err)
            throw err;

        var query = "select * from Contacts";

        dbClient.query(query,function(err,result){
            if(err)
                throw err;
            else {

                   ??????????

                res.end();
            }
        });
    });
});

app.listen(8080,function(){
    console.log('Server started');
});

sample image

【问题讨论】:

  • 你的问题离题太远了。 HTML是客户端,而数据库是服务器端。

标签: node.js postgresql express


【解决方案1】:

您可以通过使用任何 javascript 模板语言来做到这一点,其中最流行的一种是 EJS“嵌入式 javascript”,它非常容易与 node js 集成和使用

您只需创建模板并传递任何变量,如数组。

检查下面的代码,这是在 EJS 中添加模板的方式

<html >

<head>
    <meta charset="utf-8">
</head>

<body>
    <section class="home">
    <h1>Contacts list</h1>
    <ul class="list-group">
        <% for(var i=0; i<contacts.length; i++) {%>
            <li class="list-group-item">
                <span>Name: </span><%= contacts[i].name %>
                <br/>
                <span>Phone: </span><%= contacts[i].phone %>
            </li>
        <% } %>
    </ul>
    </section>
</body>

</html>

然后在您的节点中,js 路由处理程序将只呈现该模板并传递所需的数据。

app.get('????',function(req,res) {
    var dbClient = new db.Client(dbConnection);

    dbClient.connect(function(err){
        if(err)
            throw err;

        var query = "select * from Contacts";

        dbClient.query(query,function(err,result){
            if(err)
                throw err;
            else {
                 res.render('contacts.ejs', { contacts: result });  
            }
        });
    });
});

最后一步是告诉 node 它将使用 ejs 作为模板语言。

app.set('view engine', 'ejs');

别忘了npm install --save ejs

【讨论】:

  • 我做了所有这些但我得到了错误:找不到模块'ejs'
  • 你跑npm install --save ejs了吗?
  • 你能看到你的 package.json 文件中列出的 "ejs" 包吗?
  • 是的...“依赖”:{“body-parser”:“^1.18.2”,“ejs”:“^2.5.7”,“pg”:“^7.3.0 " }
  • 好的,你能检查一下你在 node_modules 中是否有一个名为 ejs 的文件夹,或者不仅仅是为了确保它是否已安装......我在你的依赖项中找不到 express 你可以尝试运行npm install express --save
【解决方案2】:

感谢 Amr Labib 的帮助

server.js

var express = require('express');
var path = require('path');
var db = require('pg');
var app = express();

app.use(express.static(path.join(__dirname,'/')));
app.set('view engine', 'ejs');

var dbConnection = "postgres://postgres:root@localhost:5432/Phonebook";


// Insert Contact

app.get('/insertContact',function(req,res){
    var dbClient = new db.Client(dbConnection);

    dbClient.connect(function(err){
        if(err)
            throw err;

        var query = "insert into Contacts (fullname,phone,mobile,address) values ($1,$2,$3,$4)";
        var fullname = req.query.fullname;
        var phone = req.query.phone;
        var mobile = req.query.mobile;
        var address = req.query.address;

        var contact = [fullname , phone , mobile , address];

        dbClient.query(query , contact , function(err){
            if(err)
                throw err;
            else {
                console.log('Contact Inserted!')    ;
                res.redirect('/');      
                res.end();
            }               
        });
    });
});


// Form Handling - Update Row / Delete Row

app.get('/handleForm',function(req,res){
    var dbClient = new db.Client(dbConnection);

    dbClient.connect(function(err){
        if(err)
            throw err;

        if(req.query.deleteBtn != null){

            var query = "delete from Contacts where id = ($1)";
            var id = [req.query.id];

            dbClient.query(query , id , function(err){
                if(err)
                    throw err;
                else {
                    console.log('Contact Deleted!') ;
                    res.redirect('/contacts.html');     
                    res.end();
                }               
            });
        } else if(req.query.updateBtn != null) {
            var query = "update Contacts set fullname=($1),phone=($2),mobile=($3),address=($4) where phone=($5)";
            var fullname = req.query.fullname;
            var phone = req.query.phone;
            var phoneHidden = req.query.phoneHidden;
            var mobile = req.query.mobile;
            var address = req.query.address;            

            dbClient.query(query , [fullname,phone,mobile,address,phoneHidden], function(err){
                if(err)
                    throw err;
                else {
                    console.log('Contact Updated!') ;
                    res.redirect('/contacts.html');     
                    res.end();
                }               
            });         
        }

    });
});


// Search contact by phone

app.get('/searchContact',function(req,res) {
    var dbClient = new db.Client(dbConnection);

    dbClient.connect(function(err){
        if(err)
            throw err;

        var query = "select * from Contacts where phone=($1)";
        var searchBoxValue = req.query.searchBoxValue;

        dbClient.query(query , [searchBoxValue], function(err,result){
            if(err)
                throw err;
            else {
                res.render('searchedContact.ejs' , {contacts: result});
                res.end();
            }               
        }); 
    });
});

// Show Contact's Table

app.get('/contacts.html',function(req,res) {
    var dbClient = new db.Client(dbConnection);

    dbClient.connect(function(err){
        if(err)
            throw err;

        var query = "select * from Contacts";

        dbClient.query(query,function(err,result){
            if(err)
                throw err;
            else {

                res.render('contacts.ejs', { contacts: result });
                res.end();
            }
        });
    });
});

app.listen(8080,function(){
    console.log('Server started');
});

contacts.ejs

    <section id="table">
        <div class="table">

            <div id="headers">
                <span id="id">id</span>
                <span id="fullname">Name</span>
                <span id="phone">Phone</span>
                <span id="mobile">Mobile</span>
                <span id="address">Address</span>
            </div>

            <% for(var i = 0; i < contacts.rows.length; i++) { %>
                    <form class="tr" action="handleForm">
                        <input type="text" id="id" name="id" class="td" readonly value= <%= contacts.rows[i].id %>>
                        <input type="text" name="fullname" class="td" value= <%= contacts.rows[i].fullname %>>
                        <input type="text" name="phone" class="td" value= <%= contacts.rows[i].phone %>>
                        <input type="text" name="mobile" class="td" value= <%= contacts.rows[i].mobile %>>
                        <input type="text" name="address" class="td" value= <%= contacts.rows[i].address %>>
                        <input type="submit" name="updateBtn" id="updateBtn" value="update" class="td">
                        <input type="submit" name="deleteBtn" id="deleteBtn" value="delete" class="td">
                        <input type="hidden" name="phoneHidden" id="phoneHidden" class="td" value=<%= contacts.rows[i].phone %> >
                    </form>
            <% } %>     
        </div>
    </section>

【讨论】:

  • 感谢您的提示,但公平地说,您必须接受 Amr Labib 的回答,而不是您的...
猜你喜欢
  • 2015-08-16
  • 2013-03-12
  • 2021-07-24
  • 2016-04-05
  • 2020-05-07
  • 2015-07-05
  • 2019-07-20
  • 1970-01-01
  • 2017-07-12
相关资源
最近更新 更多