如何使用node.js和express从数据库动态创建HTML表格?

5
我完全是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是客户端,而数据库才是服务器端。 - vitaly-t
2个回答

10

您可以通过使用任何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>

然后在您的Node.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”。 - Αntonis Papadakis
你能在你的 package.json 文件中看到 "ejs" 包吗? - Amr Labib
是的... "dependencies": { "body-parser": "^1.18.2", "ejs": "^2.5.7", "pg": "^7.3.0" } - Αntonis Papadakis
好的,你可以检查一下你的 node_modules 文件夹里是否有一个名为 ejs 的文件夹,以确保它已经安装了。另外,我在你的依赖项中找不到 express,请尝试运行 npm install express --save - Amr Labib
我不确定为什么找不到ejs......我谷歌搜索并找到了这个答案https://dev59.com/qmsz5IYBdhLWcg3wpZhF ,它可能有所帮助。 - Amr Labib
显示剩余4条评论

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>

3
谢谢您提供的建议,但公正起见,您应该接受Amr Labib的答案,而不是您自己的答案... - Martynas

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接