在我的api控制器中导入快速应用程序

时间:2018-01-08 14:06:13

标签: node.js typescript express

我正在使用Microsoft / TypeScript-Node-Starter快速模板:https://github.com/Microsoft/TypeScript-Node-Starter

我有一个 /app.ts 文件:

import * as express from 'express';
import * as apiController from './controllers/api';

const app = express();
// ...
app.get('/api', apiController.getApi);
module.exports = app;

现在,我需要从 /controllers/api.ts 中获取对该app对象的引用:

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

export let getApi = (req: Request, res: Response) => {     
    // get a list of all router pathes to display a table of all api endpoints  
    for (const key in app._router.stack) { // TypeError: cannot read property 'stack' of undefined
    }
}

console.log(app)表示该应用为空。我想它与循环依赖有关。我尝试将module.exports = app移到顶部,但这并没有帮助。

如何解决此问题?

1 个答案:

答案 0 :(得分:1)

根据API文档,reqres包含Express app实例的引用。

https://expressjs.com/en/4x/api.html#req.app

https://expressjs.com/en/4x/api.html#res.app