【问题标题】:Import express app in my api controller在我的 api 控制器中导入 express 应用程序
【发布时间】:2018-01-09 09:50:42
【问题描述】:

我正在使用 Microsoft/TypeScript-Node-Starter express 模板: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 中获取对该应用对象的引用:

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 移到顶部,但这没有帮助。

我该如何解决这个问题?

【问题讨论】:

  • 我认为问题在于_router 没有在express.d.ts 中定义。通常,下划线表示它不是公共 API,不应使用。

标签: node.js typescript express


【解决方案1】:

根据 API 文档,reqres 持有 Express app 实例的引用。

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多