Maihan Nijat
Maihan Nijat

Reputation: 9354

How to display data as JSON using Routes and Controller?

I want to keep routes separate from controller.

My route is:

'use strict';
module.exports = function(app) {
  var controller = require('../controllers/controller');

  app.route('/').get(controller.index);
};

And controller is:

exports.index = function() {
  request = new Request(
    "MYQUERY",
    function(err, rowCount) {
      if (err) {
        console.log(err);
      } else {
        console.log(rowCount + ' rows');
      }
      connection.close();
    }
  );

  request.on('row', function(columns) {
    columns.forEach(function(column) {
      if (column.value === null) {
        console.log('NULL');
      } else {
        console.log(column.value);
      }
    });
  });

  connection.execSql(request);
};

I am able to see the result in the terminal console but I want to return it as JSON to http. I can use the following if I am using controller and routes all together:

router.get('/about', function (req, res) {
  res.send('About this wiki');
})

Upvotes: 1

Views: 410

Answers (2)

Explosion Pills
Explosion Pills

Reputation: 191769

The callback function to .get (or any router request handler) takes at least two arguments: request and response. You can see this with your example:

router.get('/about', function (req, res) {
  res.send('About this wiki');
})

You could rewrite this to make the callback a named function rather than an anonymous function:

const aboutHandler = function (req, res) {
  res.send('About this wiki');
});

router.get('/about', aboutHandler);

Your controller.index is the same kind of function, so it will take those two arguments. You just have to change your function to take them:

exports.index = function (req, res) {

This will give you access to res, and you can use it as you need to do send the response via res.send or res.json if you build a JSON object by accumulating the row results. You can use request.on('end' ... to know when the query has emitted all its results.

Upvotes: 1

sparkhead95
sparkhead95

Reputation: 435

I might be misunderstanding your question, but do you mean res.json(...);?

Upvotes: 0

Related Questions