步骤一:初始化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
结果: