title: Node.js node-postgres get JSON objects from API call
body: <p>I have followed the node-postgres.org instruction at <a href="https://node-postgres.com/guides/async-express" rel="nofollow noreferrer">https://node-postgres.com/guides/async-express</a> to connect via <code>async</code>/<code>await</code> to my postgres table <code>users</code>.</p>
  
  <p>Navigating to <code>localhost:3000/users/1</code> will return the JSON string for user 1 in the browser. I have extended this a bit to return all users at <code>localhost:3000/users</code>. My <code>routes/user.js</code> script is:</p>
  
  <pre class="lang-js prettyprint-override"><code>const Router = require('express-promise-router')
  
  const db = require('../db')
  
  // create a new express-promise-router
  // this has the same API as the normal express router except
  // it allows you to use async functions as route handlers
  const router = new Router()
  
  // export our router to be mounted by the parent application
  module.exports = router
  
  router.get('/:id', async (req, res) =&gt; {
    console.log('Where id = ');
    const { id } = req.params
    const { rows } = await db.query('SELECT * FROM users WHERE id = $1', [id])
    res.send(rows[0])
  })
  
  router.get('/', async (req, res) =&gt; {
    console.log('*');
    const { rows } = await db.all('SELECT * FROM users')
    res.send(rows)
  })
  </code></pre>
  
  <p>the index for this route at <code>routes/index.js</code> is simply:</p>
  
  <pre class="lang-js prettyprint-override"><code>const users = require('./user')
  
  module.exports = (app) =&gt; {
    app.use('/users', users)
  } 
  </code></pre>
  
  <p>and the <code>db.query()</code> and <code>db.all()</code> functions that I am awaiting are in <code>db/index.js</code>:</p>
  
  <pre class="lang-js prettyprint-override"><code>const { Pool } = require('pg')
  const pool = new Pool()
  module.exports = {
      query: (text, params) =&gt; pool.query(text, params),
      all: (text) =&gt; pool.query(text)
  }
  </code></pre>
  
  <p>The routes are required in my main <code>app.js</code> file:</p>
  
  <pre class="lang-js prettyprint-override"><code>// ./app.js
  const express = require('express')
  const mountRoutes = require('./routes')
  const cons = require('consolidate')
  const path = require('path')
  const bodyParser = require('body-parser')
  const app = express()
  mountRoutes(app)
  
  // Assign Dust Engine to .dust files
  app.engine('dust', cons.dust);
  
  // Set .dust as the default extension
  app.set('view engine', 'dust');
  app.set('views', __dirname + '/views');
  
  // Set Public Folder
  app.use(express.static(path.join(__dirname, 'public')));
  
  //Body parser and Middleware
  app.use(bodyParser.json());
  app.use(bodyParser.urlencoded({
    extended: false
  }));
  
  app.get('/', function(reg, res) {
    console.log('Root');
    res.render('index', {hallo:'test'})
  });
  
  //Server 
  app.listen(3000, function() {
    console.log('Server Started on Port 3000');
  });
  </code></pre>
  
  <p>So far this works beautifully! I get the JSON strings that I want and I can build upon this sort of API by extending my routes and queries. </p>
  
  <p><strong>Question:</strong>
  How can I return my JSON object <code>rows</code> back to <code>app.js</code> to <code>res.render()</code> it there?</p>
  
  <p><em>or</em></p>
  
  <p>Can I do something like this anywhere in my app:</p>
  
  <pre><code>jsonVar = GetMyJson('/users/1');
  console.log(jsonVar);
  </code></pre>
  
  <p>returns:</p>
  
  <pre><code>[
    {
      "id": 1,
      "usr_name": "Michael"
    },
    {
      "id": 2,
      "usr_name": "Thomas"
    },
    {
      "id": 3,
      "usr_name": "Paul"
    }
  ]
  </code></pre>
  
  <p>I could then pass whatever route and parameters I want into <code>GetMyJson()</code> and deal with the resulting JSON.</p>
  
  <p>This may be a trivial question for javascript devs ...</p>
  
  <p>Thanks!</p>
  
  <p><strong>EDIT 21/12/2017</strong></p>
  
  <p>I have created a frontend script called <code>graphs.js</code> that simply logs my result when i call the fuction <code>api('/user/1')</code>. </p>
  
  <pre class="lang-js prettyprint-override"><code>var el = document.getElementById("clickMe");
  if (el.addEventListener)
      el.addEventListener("click", api, false);
  else if (el.attachEvent)
      el.attachEvent('onclick', api);
  
  var api = function(what){
      // Action
      sendRequest(what, function(result){
          if(result){
             log(result);
           }
      })
  
  }
  
  var apiEndpoint = 'http://localhost:3000/'
  function sendRequest(_path, cb) {
      var oReq = new XMLHttpRequest();
      oReq.open('GET', apiEndpoint+_path);
      oReq.onreadystatechange = function() {
          if (this.readyState === 4) {
              cb(JSON.parse(this.response));
          }
          else{
              cb(null);
          }
      }
      oReq.send();
  }
  
  function log(msg){
      console.log(msg);
  }
  </code></pre>
  
  <p><strong>BUT</strong>
  Is that a proper way of doing it in javascript?</p>