在快速js中引导后获取连接

问题描述 投票:1回答:1

我使用带有expressjs的TypeORM但是在引导之后我无法连接。

在我的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;

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

ConnectionNotFoundError: Connection "default" was not found.

['ConnectionNotFoundError:Connection“默认”未找到。','在新的ConnectionNotFoundError(C:[user] \ node_modules \ typeorm \ error \ ConnectionNotFoundError.js:19:28)','在ConnectionManager.get(C:[ user] \ node_modules \ typeorm \ connection \ ConnectionManager.js:38:19)','at Object.getConnection(C:[user] \ node_modules \ typeorm \ index.js:268:35)','at new UsersController( C:[user] \ build \ app \ controllers \ users.controller.js:7:41)','at Object。 (C:[user] \ build \ app \ routes \ users.route.js:12:19)','在Module._compile(internal / modules / cjs / loader.js:689:30)','at 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个回答
0
投票

发生此错误的原因是初始化代码“TypeORM”以异步方式运行,其余代码向前运行。解决方案是您需要在块之后注册块中的所有快速路由(createConnection({})。然后)。该文档有一个使用express的示例:

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

© www.soinside.com 2019 - 2024. All rights reserved.