欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 汽车 > 时评 > 基于express+TS+mysql+sequelize的后端开发环境搭建

基于express+TS+mysql+sequelize的后端开发环境搭建

2025/3/16 8:42:14 来源:https://blog.csdn.net/2301_77523019/article/details/146277211  浏览:    关键词:基于express+TS+mysql+sequelize的后端开发环境搭建

步骤一:初始化node环境

npm init -y

 步骤二:安装 Express、TypeScript、以及相关类型的定义文件

npm install express

npm install --save-dev typescript @types/node @types/express ts-node nodemon

npm install body-parser

npm install mysql2

npm install sequelize

 步骤三:初始化ts文件配置

创建 tsconfig.json 文件来配置 TypeScript 编译选项:

{"compilerOptions": {"target": "ES6","module": "commonjs","strict": true,"esModuleInterop": true,"skipLibCheck": true,"forceConsistentCasingInFileNames": true,"outDir": "./dist"},"include": ["src/**/*.ts"],"exclude": ["node_modules"]
}

步骤四:初始化启动类

import express from 'express';
import path from 'path';
//解析json字符串
import bodyParser from 'body-parser';class Main {private app: express.Application;private port: number;constructor(port: number) {this.app = express();this.app.use(bodyParser.json()).use(bodyParser.urlencoded({ extended: true }));this.port = port;this.getStaticData();}public start(): void {this.app.listen(this.port, () => {console.log(`服务器已启动!`);});}public use(router: express.Router, api?: string): Main {if (api) {this.app.use(api, router);} else {this.app.use(router);}return this;}private getStaticData(): void {this.app.use('/static', express.static(path.join(__dirname, './static')));console.log('静态资源已加载');}getApp(): express.Application {return this.app;}
}const main = new Main(8080);main.start();

步骤五:初始化mysql工具文件

import { Sequelize } from 'sequelize';const sequelize = new Sequelize("sd_ai_db","root","root",{host:"localhost",dialect:"mysql",timezone: '+08:00',//配置连接池pool:{max:5,min:0,idle: 10 * 1000,}
});sequelize.authenticate().then(() => {console.log('数据库连接成功');
}).catch(err => {console.error('数据库连接失败:', err);
});export default sequelize;

步骤六:编写示例服务器接口

web层:
import express, { Request, Response } from 'express'; 
import { HelloService } from '../service/HelloService';
import helloService from '../service/HelloService';
import Result from '../model/Result';class HelloWeb {private router: express.Router;private helloService: HelloService;constructor() {this.router = express.Router();this.helloService = helloService;//注册接口this.lookStartInfo();console.log("HelloWeb初始化完毕");}public getRouter(): express.Router {return this.router;}/*** 找到服务器的全部启动记录*/private lookStartInfo(): void {this.router.get('/lookStartInfo', async (req: Request, res: Response) => {const data = await this.helloService.lookStartInfo();res.json(new Result(200, "查询成功", data));})}
}//导出接口
export default new HelloWeb().getRouter();
service层:
import HelloDao from "../dao/HelloDao";class HelloService {constructor() {this.startService();console.log("HelloService加载完毕");}public async startService(): Promise<any> {return await HelloDao.create({})}public async lookStartInfo(): Promise<any> {const data = await HelloDao.findAll();return data;}}export default new HelloService();export { HelloService };
dao层:
import { INTEGER, Model } from 'sequelize';
import mysql from '../utils/mysql';class HelloDao extends Model{}HelloDao.init({id: {type: INTEGER,primaryKey: true,autoIncrement: true}
},{sequelize:mysql,tableName: 'systems',modelName: 'system',timestamps: true
})//初始化表结构
HelloDao.sync({force:false}).then(()=>{console.log('system表初始化成功');
}).catch(()=>{console.log('system表初始化失败');
})export default HelloDao;
model类: 
class Result {private code: number;private msg: string;private data: any;constructor(code: number, msg: string, data: any) {this.code = code;this.msg = msg;this.data = data;}public getCode(): number {return this.code;}public getMsg(): string {return this.msg;}public getData(): any {return this.data;}
}export default Result;

将接口配置到index.ts中:

import express from 'express';
import path from 'path';
//解析json字符串
import bodyParser from 'body-parser';
//引入Hello接口
import Hello from './web/HelloWeb';class Main {private app: express.Application;private port: number;constructor(port: number) {this.app = express();this.app.use(bodyParser.json()).use(bodyParser.urlencoded({ extended: true }));this.port = port;this.getStaticData();}public start(): void {this.app.listen(this.port, () => {console.log(`服务器已启动!`);});}public use(router: express.Router, api?: string): Main {if (api) {this.app.use(api, router);} else {this.app.use(router);}return this;}private getStaticData(): void {this.app.use('/static', express.static(path.join(__dirname, './static')));console.log('静态资源已加载');}getApp(): express.Application {return this.app;}
}const main = new Main(8080);//引入模块
main.use(Hello, '/api');//启动服务器
main.start();

 步骤七:编写启动脚本命令

编辑package.json中的scripts启动命令,编辑完成后大概是这样:

{"name": "back","version": "1.0.0","description": "","main": "index.js","scripts": {"start": "ts-node src/index.ts","dev": "nodemon src/index.ts"},"keywords": [],"author": "","license": "ISC","dependencies": {"body-parser": "^1.20.3","express": "^4.21.2","mysql2": "^3.13.0","sequelize": "^6.37.6"},"devDependencies": {"@types/express": "^5.0.0","@types/node": "^22.13.10","nodemon": "^3.1.9","ts-node": "^10.9.2","typescript": "^5.8.2"}
}

步骤八:启动服务器

npm run dev(可以一直启动,修改代码后不用重启)

npm run start

结果:

 

补充:项目文件结构 

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com