nodejs&中的路由结构expressjs

时间:2013-08-19 11:56:02

标签: node.js npm

我有以下应用程序结构

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

1。内容/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。 dbresources.js的内容

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

3。 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。 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'))
});

当我使用node和fire localhost:5000 / user运行我的应用程序时。它显示我跟随错误。

ReferenceError: sequelize is not defined

1 个答案:

答案 0 :(得分:1)

错误正是错误的。你正在使用sequelize而没有在/routes/index.js中首先定义它。如果它是您在dbconfig中创建的var,则首先需要公开它:

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

并将其导入/routes/index.js,如下所示:

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