如何使用node.js动态地从数据库创建html表并表达?

时间:2017-10-08 14:26:25

标签: node.js postgresql express

我在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

2 个答案:

答案 0 :(得分:3)

你可以使用任何javascript模板语言来做到这一点,其中最流行的是EJS&#34;嵌入式javascript&#34;它很容易与节点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 });  
            }
        });
    });
});

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

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

不要忘记npm install --save ejs

答案 1 :(得分:0)

感谢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>