0

我有以下应用程序结构

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

一、内容/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'))
});

当我使用节点运行我的应用程序并触发 localhost:5000/user 时。它向我显示以下错误。

ReferenceError: sequelize is not defined
4

1 回答 1

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...
于 2013-08-19T12:18:07.037 回答