【问题标题】:Get connection after bootstraping in express js在 express js 中引导后获取连接
【发布时间】:2019-01-10 20:03:03
【问题描述】:

我将 TypeORM 与 expressjs 一起使用,但在引导后我无法连接。

在我的app.js,我有

import 'reflect-metadata';
import { createConnection, ConnectionOptions } from 'typeorm';
// Other imports

const app: Application = express();

// Setup express-async-errors
asyncHandler;

createConnection({
  "type": "sqlite",
  "database": "database.sqlite",
  "synchronize": true,
  "logging": true,
  "entities": [
    path.join(__dirname, "app/entity/**/*.js")
  ],
}).then(async connection => {

  // Set Environment & middleware
  middleware(app);

  // setup routes
  routes(app);

  app.listen(3000);
}).catch(error => console.log(error));

 export default app;

然后,我有一个 UsersController.ts 链接到用户路线

import { Request, Response } from 'express';
import { User } from '../entity/User';
import { getConnection } from "typeorm";

class UsersController {
  private userRepository;

  constructor() {
    this.userRepository = getConnection().getRepository(User);
  }

  async index(req: Request, res: Response) {
    const users = await this.userRepository.find();

    res.json({
      users
    });
  }
}

export default UsersController;

但是,如果我尝试运行上面的代码,我总是会得到 ​​p>

ConnectionNotFoundError: Connection "default" was not found..

[ 'ConnectionNotFoundError: 未找到连接“默认”。', ' 在新的 ConnectionNotFoundError (C:[user]\node_modules\typeorm\error\ConnectionNotFoundError.js:19:28)', ' 在 ConnectionManager.get (C:[user]\node_modules\typeorm\connection\ConnectionManager.js:38:19)', ' 在 Object.getConnection (C:[user]\node_modules\typeorm\index.js:268:35)', ' 在新的 UsersController (C:[user]\build\app\controllers\users.controller.js:7:41)', ' 在对象。 (C:[用户]\build\app\routes\users.route.js:12:19)', ' 在 Module._compile (internal/modules/cjs/loader.js:689:30)', ' 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:700:10)', ' 在 Module.load (internal/modules/cjs/loader.js:599:32)', ' 在 tryModuleLoad (internal/modules/cjs/loader.js:538:12)', ' 在 Function.Module._load (internal/modules/cjs/loader.js:530:3)' ] }

我已经检查了 typeORM 在线文档,我上面的内容是设置 TypeORM 的推荐方法,所以我很困惑。

任何指向正确方向的指针都会受到赞赏。

【问题讨论】:

    标签: node.js typescript typeorm


    【解决方案1】:

    出现错误是因为初始化代码“TypeORM”异步运行,其余代码向前运行。解决的办法是你需要在之后的块中注册所有的快速路由(createConnection({}).then)。该文档有一个使用 express 的示例:

    http://typeorm.io/#/example-with-express

    【讨论】:

    • 仅供参考。我花了很多时间让事情在没有这种方法的情况下工作,但这似乎是不可能的,所以我想这是这个问题的唯一答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-15
    • 2012-07-12
    • 2016-11-04
    • 1970-01-01
    • 2021-06-28
    相关资源
    最近更新 更多