Ashwin Hegde
Ashwin Hegde

Reputation: 1771

route structure in nodejs & expressjs

I have following Application structure

/routes
  - index.js
dbconfig.js
dbresources.js
server.js

1. Content of /routes/index.js

exports.index = function(req, res){
  console.log("Routes Successfully");
  sequelize.query("SELECT * FROM users_tbl").success(function(rows) {
    res.format({
      json: function() {
        res.send(rows);
      }
    });
    // res.jsonp(rows);
  }).error(function(error) {
    console.log(error);
  });
};

2. Content of dbresources.js

module.exports = {
    database: {
        name: "dbproject",
        host: "root",
        password: ""
    }
}

3. Content of dbconfig.js

var Sequelize = require('sequelize')
    , mysql = require('mysql');

config = require("./dbresources");
db = config.database;

var sequelize = new Sequelize(db.name, db.host, db.password, {
    dialect: 'mysql'
});

4. Content of server.js

var express   = require('express')
  , http      = require('http')
  , app       = express()
  , http      = require('http')
  , routes    = require('./routes')
  , path      = require('path');

app.configure(function() {
    app.set('port', process.env.PORT || 5000);
    app.use(express.bodyParser());
    app.set(express.methodOverride());
    app.set(express.router);
    app.use(express.static(__dirname + '/src'));
});

app.get('/user', routes.index);

http.createServer(app).listen(app.get('port'), function(){
    console.log("\n\n\tNode (Express) server listening on port " + app.get('port'))
});

When i am running my apps using node and fire localhost:5000/user. It shows me following error.

ReferenceError: sequelize is not defined

Upvotes: 0

Views: 2262

Answers (1)

Andreas Hultgren
Andreas Hultgren

Reputation: 14953

The error is exactly what's wrong. You're using sequelize without defining it first it in /routes/index.js. If it's the var you've created in dbconfig, you first need to expose it like so:

// The rest of the code...
exports.sequelize = sequelize;

and import it in /routes/index.js like so:

var sequelize = require('./dbconfig').sequelize;
// The rest of the code...

Upvotes: 1

Related Questions