搭建服务器直接读取数据库时,有些逻辑会比较麻烦,性能上也不是很好,选用orm框架式一个很好的选择,我这里使用express+sequilize
安装sequilize
npm install --save sequelize
创建sequilize文件:
const { Sequelize } = require('sequelize');// 创建Sequelize实例
const sequelize = new Sequelize('lanya', 'root', '123456', {host: '127.0.0.1',dialect: 'mysql', // 或者 'postgres', 'sqlite', 'mssql'logging: false
});module.exports = sequelize;
创建Model:
// models/User.js
const { DataTypes } = require('sequelize');
const sequelize = require('../config/sql.config');const testModel = sequelize.define('part1', {id: {type: DataTypes.INTEGER,autoIncrement: true,primaryKey: true},category: {type: DataTypes.STRING,},subCategory: {type: DataTypes.STRING,},subTitle: {type: DataTypes.STRING,},question: {type: DataTypes.STRING,},iconPath: {type: DataTypes.STRING,},addTime: {type: DataTypes.STRING,},modifyTime: {type: DataTypes.STRING,},isCollected: {type: DataTypes.STRING,},
}, {// 由于表已经存在,timestamps 设置为 falsetimestamps: false,// 设置表的名字freezeTableName: true,
});module.exports = testModel;
引入到对应的文件中,并声明同步方法
//sequilize
const testModel = require("./miniUser")// 同步所有模型到数据库
async function syncAllModels() {await testModel.sync();
}module.exports = syncAllModels
在服务器启动时,执行方法
const express = require('express')
const cors = require('cors')
const syncAllModels = require("./models/index")//引入路由
const manage = require("./router/manage/index")
const mini = require("./router/miniprogram/index")//创建服务器
const app = express()//跨域方案
app.use(cors())
app.use(express.urlencoded({ extended: false }))
app.use(express.json())//配置orm框架管理
syncAllModels()app.listen(888, () => {console.log('启动了');
})
此时,已经配置好了,下面就可以使用对应的api了