前言
- 苦于网上没有整合两大框架的步骤,故自己整理了一下用于自我记录。
- 本demo用到的框架、插件和技术的文档地址:
全局安装typescript
1.首先需要在全局安装typescript
npm install typescript -g
2.安装完成typescript后输入以下代码查看版本
$ tsc -v
Version 4.4.3
如出现版本就表示安装成功
安装egg
我们需要先全局安装egg,在初始化typescript项目。
npm init egg --type=ts
初始化创建好项目后,安装项目依赖
npm i
安装typeorm
npm install typeorm --save
简单安装这些我们就可以先试试能否成功启动项目,启动浏览器输入地址出现下图说明启动成功!
配置typeorm连接mysql文件
我们需要使用到一个插件:egg-ts-typeorm用于连接数据库
npm install -S egg-ts-typeorm
安装好插件,到config配置启用插件
// {app_root}/config/plugin.ts
const plugin: EggPlugin = {
typeorm: {
enable: true,
package: 'egg-ts-typeorm',
},
}
到根目录中配置ormconfig.yml,内容如下
default: # 默认连接
entitiesdir: "app/entities"
最后到config/config.default.ts中配置数据库连接信息
// {app_root}/config/config.default.ts
config.typeorm = {
client: {
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'test',
password: 'test',
database: 'test',
synchronize: true,
logging: false
}
}
创建实体类
到app目录下创建entities目录
在entities目录下创建User.ts
import { Entity, PrimaryGeneratedColumn,Column } from "typeorm";
@Entity()
export default class User {
@PrimaryGeneratedColumn({
type: 'int',
comment:'主键id'
})
id: number;
@Column({
type: 'varchar',
length:50,
comment:'账号'
})
account: string;
@Column({
type: 'varchar',
length:50,
comment: '密码'
})
password: string;
}
编写controller
在controller目录下创建user.ts编写
import { Controller } from "egg";
export default class UserController extends Controller {
public async index(){
const {ctx} = this;
ctx.body = await ctx.repo.User.find();
}
}
修改router.ts
import { Application } from 'egg';
export default (app: Application) => {
const { controller, router } = app;
router.get('/', controller.home.index);
router.get('/user/list', controller.user.index);
};
好了,我们基本的已经写完了,接下来就看看能不能拿到数据了
报错: nodejs.TypeError: Cannot read property ‘find’ of undefined
这个错误就是实体类不是export default 导致ctx.repo仓库中没有找到user才出现的报错
当然这个只是我的demo 也有比较完整的示例项目可以学习:点击跳转