node.js - 为什么我的 module.exports 不起作用?

标签 node.js

这是我的基本 node.js 应用程序,只有两个文件:

应用程序.js

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

module.exports = { 
  test: "test"
};


// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
    // defining  middlewares

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




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

和我的 index.js:

var server = require('../app');
exports.index = function(req, res){
    console.log(server);
    res.send('Hello world');
};

我的问题是当我转到 http:\\localhost:3000 时,我在我的控制台中看到 {} 而不是 {test: "test"} ,看起来 module.eports 无法正常工作。为什么?

最佳答案

需要 index.js来自内部 app.js ,然后需要 app.js来自内部 index.js ,对我来说看起来像代码味道。此外,如果您使用 var app = module.exports = express()然后 Express 能够将您的应用程序视为中间件(例如,您可以有第二个应用程序 requires 第一个应用程序,并将一些请求传递给它。

当我需要访问 app 时在另一个必需的文件中,我执行以下操作:

// ./routes/index.js
module.exports = function(app){
  var routes = {};
  routes.index = function(req, res){
    console.log(app.myConfig);
    res.send('Hello world');
  };
  return routes;
};

// ./app.js
var app = module.exports = express();
app.myConfig = {foo:'bar'};
var routes = require('./routes/index.js')(app);

关于node.js - 为什么我的 module.exports 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17305784/

相关文章:

jQuery 没有向 node.js 服务器发送自定义 header CORS 请求,或者服务器没有收到?

node.js - #!/usr/bin/env : No such file or directory

node.js - Mongodb 日志泛滥

javascript - 如何使用 npm 发布客户端脚本?

javascript - 为什么 Mongoose 想要将我的字符串转换为 ObjectId?

javascript - 我可以使用 express.js 创建 web api 而没有安装 node.js 吗?

node.js - nextTick vs setImmediate,直观解释

node.js - 如何在 Meteor 的 HTTP.call() 中将额外的选项传递给 Node?

node.js - Node 缓存的导出对象已损坏

node.js - 如何注销 Spotify API 身份验证流程演示