为什么我不能把app在Express 4中传递给控制器?

时间:2022-10-24 21:04:40

since I have start my first project, i was working on it and use express 4. but when I pass the app.locals to the controller, it was a empty object. I do not know what to do now,please help.

因为我已经开始了我的第一个项目,我正在做它并且使用express 4。但当我将app.local传递给控制器时,它是一个空对象。我不知道现在该做什么,请帮忙。

Here is my project structure:

以下是我的项目结构:

app (home directory)

应用程序(主目录)

-->controller(folder)
---->webroot.js

- - >控制器(文件夹)——> webroot.js

-->router(folder)
----> index.js

- - >路由器(文件夹)——> index.js

-->app.js

- - > app.js

app.js

important part:

重要的部分:

...  
app.set('x', '123')
...   
module.exports = app;

router/index.js

var express = require('express');
/*controllers here*/
var webroot = require('../controllers/webroot')

var router = express.Router();

/* GET home page. */
router.get('/', webroot.index);

controller/webroot.js

var app = require('../app');

console.log(app.get('x'))  //Object #<Object> has no method 'get'

exports.index = function(req,res){
    //code here
})    

1 个解决方案

#1


0  

This may be due to a cycle of dependencies.

这可能是由于依赖的循环。

app.js -> router/index.js -> controllers/webroot.js -> app.js -> ...

That is, assuming app.js includes another "important part" of requiring router/index, such as.

也就是说,假设app.js包含另一个需要路由器/索引的“重要部分”,例如。

// ...
app.use(require('./router'));
// ...
app.locals.title = '123';
// ...
module.exports = app;

In handling cycles, Node.js will have only executed a portion of app.js when webroot.js requires app.js it again, which is only up to the inclusion of router/index.js.

在处理周期,节点。当webroot时,js将只执行app.js的一部分。js再次需要app.js,这只取决于路由器/index.js的包含。


To work with the cycle, you'll want to order the statements so enough of app.js is executed before starting the cycle:

要处理循环,您需要对语句进行排序,以便在开始循环之前执行足够的app.js:

// ...

// modify shared state
app.locals.title = '123';

// then load dependencies with cycles
app.use(require('./router'));

// ...

#1


0  

This may be due to a cycle of dependencies.

这可能是由于依赖的循环。

app.js -> router/index.js -> controllers/webroot.js -> app.js -> ...

That is, assuming app.js includes another "important part" of requiring router/index, such as.

也就是说,假设app.js包含另一个需要路由器/索引的“重要部分”,例如。

// ...
app.use(require('./router'));
// ...
app.locals.title = '123';
// ...
module.exports = app;

In handling cycles, Node.js will have only executed a portion of app.js when webroot.js requires app.js it again, which is only up to the inclusion of router/index.js.

在处理周期,节点。当webroot时,js将只执行app.js的一部分。js再次需要app.js,这只取决于路由器/index.js的包含。


To work with the cycle, you'll want to order the statements so enough of app.js is executed before starting the cycle:

要处理循环,您需要对语句进行排序,以便在开始循环之前执行足够的app.js:

// ...

// modify shared state
app.locals.title = '123';

// then load dependencies with cycles
app.use(require('./router'));

// ...