简体   繁体   English

使用Nodejs和大规模创建控制器

[英]Creating a Controller using Nodejs and massive

Using massive postgreSQL driver , I am able to connect to postgreSQL and get records from database. 使用大量的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);
    });

This code logs data to console window. 此代码将数据记录到控制台窗口。 But I want to create an end point and send the response back to the client. 但是我想创建一个端点,并将响应发送回客户端。

Tried for sample on how to create controller using Node and massive , but not much luck. 尝试获取有关如何使用Node和Massive创建控制器的示例,但是运气不高。

It sounds like you want to create a HTTP endpoint, is that correct? 听起来您想创建一个HTTP端点,对吗?

For this, you will probably want to use express.js . 为此,您可能需要使用express.js

There are plenty of great tutorials out there on create a HTTP server with express, however this will get you started: 有很多关于使用express创建HTTP服务器的优秀教程,但这将使您入门:

Install the express module via the node package manager. 通过节点程序包管理器安装Express模块​​。

From your terminal/command line, type: 在终端/命令行中,输入:

cd project-name
npm install express --save

Modify your node server to the following: 将您的节点服务器修改为以下内容:

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);

This application will listen on port 3000, and respond to requests to '/', eg http://localhost:3000/ . 该应用程序将侦听端口3000,并响应对“ /”的请求,例如http:// localhost:3000 / The database will be queried and the result will be send as the response to the HTTP request. 将查询数据库,并将结果作为对HTTP请求的响应发送。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM