0

使用大量的 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 和大规模创建控制器的示例,但运气不佳。

4

1 回答 1

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 请求的响应发送。

于 2016-06-27T14:44:19.417 回答