错误:无法读取undefined的属性

时间:2014-07-23 09:45:20

标签: javascript node.js

我正在尝试使用Express配置我的应用程序,如下所示,但我在执行此操作时遇到错误:

server.js

var express = require('express');
var env = process.env.NODE_ENV = process.env.NODE_ENV || 'devleopment';
var app = express();
var config = require('./server/config/config')[env];
require('./server/config/express')(app, config);
app.listen(config.port);
console.log('Listening on port ' + config.port + '...');

config.js

var path = require('path');
var rootPath = path.normalize(__dirname + '/../../');

module.exports = {
  development: {
    db: 'localhost',
    rootPath: rootPath,
    port: process.env.PORT || 3003
  },
  production: {
    rootPath: rootPath,
    db: 'localhost',
    port: process.env.PORT || 80
  }
}

但是,在控制台上找到它,我收到此错误消息:

    app.set('views', config.rootPath + '/server/views');
                           ^
TypeError: Cannot read property 'rootPath' of undefined
    at module.exports (.\server\config\expr
ess.js:13:28)
    at Object.<anonymous> (.\server.js:9:35
)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3
23 Jul 10:38:13 - [nodemon] app crashed - waiting for file changes before starti
ng...

我认为它来自rootPath的初始化。但是,我无法找到错误的地方。 请问如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

假设你没有设置process.env.NODE_ENV而且它使用默认值,那么你的问题是一个简单的拼写错误

process.env.NODE_ENV || 'devleopment';

应该是

process.env.NODE_ENV || 'development';

您的配置文件不会导出对象devleopment,因此会返回undefined