Surya prakash Patel
Surya prakash Patel

Reputation: 1522

How use controller function in route file - npm

I am using express with ejs in npm. I created a folder controller to write all controllers in side and write a controller home.js Code is:

var config = require('../../config/config');
exports.banners =function  (req, res)
{

       connection.connect(function(err) {
        if (!err) 
        { 

        console.log('You are now connected...');

        connection.query('SELECT * FROM banner_management WHERE banner_status ="Active" AND banner_type = "home_page" Limit 0,1', function(err, results) {
        if (err) throw err
        return results;
        var data = results ;
        console.log(data)

        //console.log(results[0].id)
        //console.log(results[0].banner_name)
        console.log(results[0].banner_image)
        //console.log(results[0].banner_url)
        })}
    });
    }

Now i am using this controller function in route file, but not getting data in view file. Code of route is:

/* GET home page. */
router.get('/', function(req, res, next) {

  var home = require('../app/controllers/home');
  console.log(home.banners);
  res.render('index', { title: 'Medical Tourism-Arogyata',data : home.banners, baseUrl: 'http://localhost:3000/' });
});

Upvotes: 1

Views: 78

Answers (1)

Mahasooq
Mahasooq

Reputation: 209

This is how you write the controllers and use them in a route.

your home.js controller file

var config = require("../../config/config");

exports.banners = function(req, res, next) {
  connection.connect(function(err) {
    if (!err) {
      console.log("You are now connected...");

      connection.query(
        'SELECT * FROM banner_management WHERE banner_status ="Active" AND banner_type = "home_page" Limit 0,1',
        function(err, results) {
          if (err) res.status(500).send(err);
          res.render('index', { title: 'Medical Tourism-Arogyata',data : results.banners, baseUrl: 'http://localhost:3000/' });          
        }
      );
    }
  });
};

and the router as the following.

var home = require('../app/controllers/home');

/* GET home page. */
router.get('/', home.banners);

Upvotes: 1

Related Questions