我将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;
但是,如果我尝试运行上面的代码,我总会得到
ConnectionNotFoundError: Connection "default" was not found.
。['ConnectionNotFoundError:找不到连接“默认”。, '位于新的ConnectionNotFoundError(C:[用户] \ 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)', '在新的UsersController上(C:[user] \ build \ app \ controllers \ users.controller.js:7:41)', '在对象。 (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(内部/模块/cjs/loader.js:538:12)', 'at Function.Module._load(internal / modules / cjs / loader.js:530:3)']
我已经检查了typeORM的在线文档,上面介绍的是建议的设置TypeORM的方法,所以我很困惑。
任何指向正确方向的指针都会受到赞赏。
答案 0 :(得分:0)
发生此错误是因为初始化代码“ TypeORM”异步运行,而其余代码向前运行。解决方案是,您需要在此之后在块中注册所有快速路由(createConnection({})。then)。该文档提供了一个使用express的示例: