如何在js中使用PostgreSQL mod for vertx?

时间:2014-06-19 16:32:58

标签: javascript jquery ajax postgresql vert.x

嗨我是vertx的新手,我希望使用https://github.com/vert-x/mod-mysql-postgresql作为服务 我将此代码用于我的Web服务器

  var vertx = require('vertx');
  var console = require('vertx/console');

  var Server = vertx.createHttpServer();

  Server.requestHandler(function (req) {
      var file = req.path() === '/' ? 'index.html' : req.path();
      if (file === '/foo') {
          foo(req);
      }    
      else{ 
       req.response.sendFile('html/' + file);
      }
  }).listen(8081);

  function foo(req) {    
      req.bodyHandler(function (data) {
            //data is json {name:foo, age:13}   i want insert this in any table in postgre
            //do  
           var dataresponse= messagefrompostgre;//e: {status:"ok", code:200, message: "its ok"}
          req.response.putHeader("Content-Type", "application/json");                            
          req.response.end(dataresponse);
      });
  }

这是我的活动点击按钮

$.ajax({
                data:   {name:foo, age:13} ,
                url:   '/foo',
                type:  'post',
                dataType: 'json', 
                complete:  function (response) {
                        alert(JSON.stringify(response));                      
                }
          });

1 个答案:

答案 0 :(得分:0)

我找到了怎么做:

  var vertx = require('vertx');
  var console = require('vertx/console');//TODO: remove
  var eventBus = vertx.eventBus;

  var Server = vertx.createHttpServer();

  Server.requestHandler(function (req) {     
      var file = req.path() === '/' ? 'index.html' : req.path();
      if (file === '/foo') {
          foo(req);
      }
      else{
       req.response.sendFile('html/' + file);
      }
  }).listen(8081);  

  function foo(req) {    
      req.bodyHandler(function (data) {
            //data is json {name:foo, age:13}                   
            var jsona={
                      "action" : "raw",
                      "command" : "select * from test"
                    }             

            eventBus.send("PostgreSQL-asyncdb",jsona, function(reply) {
            req.response.putHeader("Content-Type", "application/json");                          
            req.response.end(JSON.stringify(reply));                
            }); 
      });
  }   

并返回:

{"message":"SELECT 6","rows":6,"fields":["testt"],"results":[["lol"],["lolŕ"],["lol2"],["lol2"],["testlol"],["testlolp"]],"status":"ok"}