0

Using massive postgreSQL driver , I am able to connect to postgreSQL and get records from database.

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.

1 Answer 1

1

It sounds like you want to create a HTTP endpoint, is that correct?

For this, you will probably want to use express.js.

There are plenty of great tutorials out there on create a HTTP server with express, however this will get you started:

Install the express module via the node package manager.

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/. The database will be queried and the result will be send as the response to the HTTP request.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.