使用Nodejs和大量创建控制器

时间:2016-06-27 12:45:36

标签: node.js postgresql express controller massivejs

使用大量的postgreSQL驱动程序,我能够连接到postgreSQL并从数据库中获取记录。

var Massive = require("massive");

var connectionString = "postgres://postgres:postgres@localhost/postgres";
var db = Massive.connectSync({connectionString : connectionString});


  db.query("Select * from company", function (err, data) {
        console.log(data);
    });

此代码将数据记录到控制台窗口。但我想创建一个终点并将响应发送回客户端。

尝试了一些关于如何使用Node创建控制器的示例和大量但没有太多运气。

1 个答案:

答案 0 :(得分:1)

听起来你想要创建一个HTTP端点,这是正确的吗?

为此,您可能希望使用express.js

有很多很棒的教程可以创建一个带有express的HTTP服务器,但这会让你开始:

通过节点包管理器安装express模块​​。

在终端/命令行中输入:

cd project-name
npm install express --save

将您的节点服务器修改为以下内容:

var Massive = require("massive")
  , http = require("http") // import http
  , express = require("express") // import express
  , app = express(); // instantiate your app

/* database config */
var connectionString = "postgres://postgres:postgres@localhost/postgres";
var db = Massive.connectSync({connectionString : connectionString});

/* http routes */
app.get("/",function(req,res){
  // req is the request object
  // res is the response object
  db.query("Select * from company", function (err, data) {
    // send a http response with status code 200 and the body as the query data. 
    res.status(200).send(data);
  });
});

/* listen in port 3000 */
var server = http.createServer(app);
server.listen(3000);

此应用程序将侦听端口3000,并响应对'/'的请求,例如http://localhost:3000/。将查询数据库,结果将作为对HTTP请求的响应发送。