结合node.js和postgresql,创建一个demo

 

模型简介:用node.js创建一个http服务器,使用浏览器访问相应的地址,显示数据库信息。

 

   注:该demo建立得比较简单,数据库操作就是查询某张表的数据,然后将查询出来的数据以JSON格式显示在浏览器上

1)流程简介
  该demo一共包含4个文件:index.js   server.js    router.js    function.js
  其中index.js中连接了数据库,连接成功后,调用server启动函数。
      server.js 创建http服务器,并指定端口。
      router.js 路由器,根据url地址,调用不同的函数
      function.js 各个函数的具体实现(此demo中只有一个)

2)  代码实现

  index.js

//加载相应的模块,这儿使用的是postgresql数据库,因此加载的模块是pg。使用不同的数据库可以加载相应
的模块
var pg = require('pg');

//加载内部模块
var server = require("./server");
var router = require("./router");
var func = require("./function");

//将url路径对应到相应的函数
var handle = {};
handle["/"] = func.select;
handle["/select"] = func.select;

//构造连接数据库的连接字符串:"tcp://用户名:密码@ip/相应的数据库名"
var conString = "tcp://postgres:postgres@localhost/my";
var client = new pg.Client(conString);  //构造一个数据库对象

//连接数据库,连接成功,执行回调函数
client.connect(function(error, results) {
     if(error){
            console.log('ClientConnectionReady Error: ' + error.message);
            client.end();
            return;
        }
        console.log("client.connect OK.\n");
    server.start(client,router.route,handle); //启动server
});


server.js

 

 

//加载对应的模块
var http = require("http");
var url = require("url");

function start(client,route,handle)
{
    //创建http服务器
    http.createServer(function(request,response){
        var pathname = url.parse(request.url).pathname;
        console.log("Request for " + pathname + " received.");
        route(client,handle,pathname,response);
    }).listen(8888);   //指定端口

    console.log("Server has started.");
}

exports.start = start;


router.js

 

 

function route(client,handle,pathname,response){
    console.log("About to route a request for " + pathname);

    if(typeof handle[pathname] === 'function'){
        handle[pathname](client,response);  //执行对应的函数
    }else{
        console.log("No request handle found for " + pathname +'\n');
        response.writeHead(404,{"Content-Type":"text/plain"});
        response.write("404 Not found");
        response.end();
    }
}

exports.route = route;

 

function.js

 

 

function select(client,response)
{
    console.log("Request handler 'select' was called.");
    //执行相应的sql语句
    client.query("select * from teacher;",function(error,results){
        console.log("in callback function.\n");
        if (error)
        {
            console.log("error");
            console.log('GetData Error: ' + error.message);
            client.end();
            return;
        }
        if(results.rowCount > 0)
        {
            //callback(results);
            //指定为json格式输出
            response.writeHead(200,{"Content-Type":"application/json"});       

            //先将results 字符串内容转化成json格式,然后响应到浏览器上

 response.write(JSON.stringify(results)); response.end(); } });}

exports.select = select;

 

 

 

 

 

 

3) 执行结果

  (1)  http://localhost:8888/select

        1) 后台显示:

                client.connect OK.

                Server has started.

                Request for /select received.

                About to route a request for /select

                Request handler 'select' was called.

                in callback function.

       2) 浏览器显示:

          

{

    "command":"SELECT",

    "rowCount":2,

    "oid":null,

    "rows":

        [

            {

                 "id":"1",

                 "name":"aaa",

                 "pwd":"111"

             },

             {

                 "id":"2",

                 "name":"bbb",

                 "pwd":"222"

              }

         ]

}


(2)  http://localhost:8888/

        1) 后台显示:

                client.connect OK.

                Server has started.

                Request for /  received.

                About to route a request for /

                Request handler 'select' was called.

                in callback function.

       2) 浏览器显示:同上   //由于在index.js文件中指定两种情况都访问同一个函数

 

 

 

  • 6
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值