日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 >

mysql建表的auto_increment_koa2+koa+mysql快速搭建nodejs服务器

發(fā)布時間:2025/3/21 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mysql建表的auto_increment_koa2+koa+mysql快速搭建nodejs服务器 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

用koa的腳手架koa-generator可以快速生成項目骨架,可以用于發(fā)開或者測試接口
https://github.com/hellojinjin123/node-koa2-template

1. 全局安裝koa-generator(不用全局安裝koa)

項目名字fast-koa

npm install koa-generator -gkoa2 fast-koacd fast-koanpm install

目錄結(jié)構(gòu)如下
-bin // www 項目啟動目錄 node ./www
-public // 靜態(tài)網(wǎng)站放置目錄 也就是vue dist代碼放置的地 項目入口index.html
-routes // 路由
-views // 視圖 服務(wù)器渲染使用的模板
-app.js // 項目入口
-packaga.json

2. 啟動項目

// package.json "scripts": { "start": "node bin/www", "dev": "./node_modules/.bin/nodemon bin/www", "prd": "pm2 start bin/www", "test": "echo "Error: no test specified" && exit 1" }

運行npm run dev開啟服務(wù)器
同時可以看到generator自帶了nodemon(Nodemon 是一款非常實用的工具,用來監(jiān)控你 node.js 源代碼的任何變化和自動重啟你的服務(wù)器)
如下圖:服務(wù)器啟動了

3. 項目入口app.js

// app.jsconst Koa = require('koa')const app = new Koa()const views = require('koa-views')const json = require('koa-json')const onerror = require('koa-onerror')const bodyparser = require('koa-bodyparser')const logger = require('koa-logger')const index = require('./routes/index')const users = require('./routes/users')// error handleronerror(app)// middlewaresapp.use(bodyparser({ enableTypes:['json', 'form', 'text']}))app.use(json())app.use(logger())app.use(require('koa-static')(path.resolve(__dirname, config.publicPath))))app.use(views(__dirname + '/views', { extension: 'pug'}))// loggerapp.use(async (ctx, next) => { const start = new Date() await next() const ms = new Date() - start console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)})// routesapp.use(index.routes(), index.allowedMethods())app.use(users.routes(), users.allowedMethods())// error-handlingapp.on('error', (err, ctx) => { console.error('server error', err, ctx)});module.exports = app

可以在根目錄路添加config.js 把一些公共的配置放入 比如數(shù)據(jù)庫信息,端口,靜態(tài)資源路徑等

// config.jsconst path = require('path');const config = { // 項目啟動監(jiān)聽的端口 port: 3000, publicPath: 'public', logPath: 'logs/koa-template.log', // 數(shù)據(jù)庫配置 database: { HOST: 'xxx', // 數(shù)據(jù)庫地址 USERNAME: 'xxx', // 用戶名 PASSWORD: 'xxx', // 用戶密碼 DATABASE: 'xxx', // 數(shù)據(jù)庫名 PORT: 3306 // 數(shù)據(jù)庫端口(默認(rèn): 3306) }};module.exports = config;

4. koa-static 靜態(tài)資源中間件

app.use(require('koa-static')(path.resolve(__dirname, config.publicPath))))
koa-generator已經(jīng)配置了靜態(tài)資源中間件,只要放入public目錄,靜態(tài)網(wǎng)站就可以運行
瀏覽http://localhost:3000/,服務(wù)器會優(yōu)先讀取public下的index.html
如果沒有index.html,服務(wù)器會根據(jù)路由,判斷'/'是否有內(nèi)容返回,沒有對應(yīng)路由則返回404 not found
因為koa-generator默認(rèn)設(shè)置了路由,所以服務(wù)器運行返回了Hello Koa 2!
如下:

router.get('/', async (ctx, next) => { await ctx.render('index', { title: 'Hello Koa 2!' })})

5. 添加models目錄

相當(dāng)于服務(wù)器數(shù)據(jù)層,存放數(shù)據(jù)庫模型(相當(dāng)于建表),使用Sequelize進(jìn)行mysql操作

const { sequelize, Sequelize } = require('../config/db')const { DataTypes, Model } = Sequelizeclass Admin extends Model { /** * @description: 添加管理員 * @param {*} username * @param {*} password * @return {*} 返回添加的數(shù)據(jù) */ static async createAdmin({ username, password }) { return await this.create({ username, password }) } /** * @description: 根據(jù)id修改管理員密碼 * @param {*} id * @return {*} 返回修改的數(shù)據(jù) */ static async updatepwdById({id, password}) { return await this.update({ password }, { where: { id } }) } /** * @description: 根據(jù)id刪除管理員 * @param {*} id * @return {*} */ static async deleteById(id){ return await this.destroy({ where: { id } }) }}// 初始化表結(jié)構(gòu)Admin.init( { id: { type: DataTypes.INTEGER, allowNull: false, //非空 autoIncrement: true, //自動遞增 primaryKey: true //主鍵 }, username: { type: DataTypes.STRING, field: "username", allowNull: false, unique: true // 唯一約束 用戶名不能重復(fù) }, password: { type: DataTypes.STRING, allowNull: false }, active: { type: DataTypes.BOOLEAN, allowNull: false, defaultValue: true } }, { underscored: true, //額外字段以下劃線來分割 timestamps: true, //取消默認(rèn)生成的createdAt、updatedAt字段 createdAt: "created_at", updatedAt: "updated_at", freezeTableName: true, // Model 對應(yīng)的表名將與model名相同 comment: "管理員表類", // paranoid: true //虛擬刪除 sequelize, // 我們需要傳遞連接實例 // modelName: 'Admin', // 我們需要選擇模型名稱 // tableName: 'Admin' // 表名}) // 創(chuàng)建表格 ; (async () => { await Admin.sync(); console.log("Admin表剛剛(重新)創(chuàng)建!"); // 這里是代碼 })()// 定義的模型是類本身// console.log(User === sequelize.models.User); // truemodule.exports = Admin

6. mysql數(shù)據(jù)庫的使用(Sequelize stars 23.6k in github )

Sequelize 是一個基于 promise 的 Node.js ORM, 目前支持 Postgres, MySQL, MariaDB, SQLite 以及 Microsoft SQL Server. 它具有強大的事務(wù)支持, 關(guān)聯(lián)關(guān)系, 預(yù)讀和延遲加載,讀取復(fù)制等功能。

Sequelize 遵從 語義版本控制。 支持 Node v10 及更高版本以便使用 ES6 功能。https://www.sequelize.com.cn/core-concepts/model-basics

安裝mysql&sequelize

npm install --save mysql mysql2npm install --save sequelize

安裝sequelize之后,在config目錄下創(chuàng)建db.js,進(jìn)行數(shù)據(jù)庫連接設(shè)置

const Sequelize = require('sequelize');const db = require('./index').db// 初始化數(shù)據(jù)庫const sequelize = new Sequelize(db.database, db.username, db.password, { host: db.host, dialect: 'mysql', pool: { max: 5, min: 0, idle: 10000 }})//測試數(shù)據(jù)庫鏈接sequelize.authenticate().then(function() { console.log("數(shù)據(jù)庫連接成功");}).catch(function(err) { //數(shù)據(jù)庫連接失敗時打印輸出 console.error(err); throw err;}); module.exports = { sequelize, Sequelize }

7. 添加controllers目錄

有了模型層對操作數(shù)據(jù)庫的支持,就可以進(jìn)行業(yè)務(wù)操作了,也就是控制器目錄(在這個層可以放心調(diào)用models層方法進(jìn)行curd)

// 導(dǎo)入模型const Admin = require('../models/admin')module.exports = { async getAllAdmins(ctx, next) { try { let data = await Admin.findAll() ctx.body = { msg: 1001, data } } catch (err) { ctx.body = { code: -1, msg: 1000, } } await next(); }, async createAdmin(ctx, next) { let req = ctx.request.body if (!req.username || !req.password) { ctx.body = { code: -1, msg: 1002 } return await next(); } try { let data = await Admin.createAdmin(req) ctx.body = { msg: 1003, data } } catch (err) { ctx.body = { code: -1, msg: 1000 } } await next(); }, async updatepwdById(ctx, next) { let req = ctx.request.body if (req.id && req.password) { try { await Admin.updatepwdById(req) ctx.body = { msg: 1004 } } catch (err) { ctx.body = { code: -1, msg: 1000 } } } else { ctx.body = { code: -1, msg: 1002 } } await next(); }, async deleteById(ctx, next) { let query = ctx.request.query // 獲取get請求參數(shù) if (query && query.id) { try { await Admin.deleteById(query.id) ctx.body = { msg: 1005 } } catch (err) { ctx.body = { code: -1, msg: 1000 } } } else { ctx.body = { code: -1, msg: 1002 } } await next(); }}

8. 路由配置

// app.js 中添加// routesconst admin = require('./routes/admin')app.use(admin.routes(), admin.allowedMethods())

到此為止,一個完整的請求(接口)就處理完成了
比如請求 http://localhost:3000/admin/getAllAdmins

koa經(jīng)歷的簡單過程:

  • 瀏覽器發(fā)出請求 -> 中間件 ->路由中間件 -> 中間件 -> 中間件若干回調(diào) -> 瀏覽器收到響應(yīng)
  • 路由:
    • router.get/post -> controllers.func -> models.func-> mysql
    • 請求行為 -> 業(yè)務(wù)邏輯 -> 模型支持 -> 入庫

    9. 配置自定義的中間件處理日志和response消息

    可以參考github代碼

    10. 附上一個很好理解的中間件原理的簡析

    // 根目錄下test.js// koa2 中間件原理簡析// 中間件的倉庫const arr = [ async (next) => { console.log(1); await next(); console.log(2); }, async (next) => { console.log(3); await new Promise((resolve, reject) => { setTimeout(() => { resolve( console.log(4) ); }, 3000); }); // 異步操作 await 會等待后面的promise resolve 后再向下執(zhí)行 await next(); console.log(5); }, async (next) => { console.log(6); }, async (next) => { // 不會執(zhí)行 因為上一個函數(shù)中沒有執(zhí)行next console.log(7); await next(); console.log(8); }, async (next) => { // 不會執(zhí)行 因為前面的函數(shù)中沒有執(zhí)行next console.log(9); }];function fun(arr) { function dispose(index) { const currentFun = arr[index]; const next = dispose.bind(null, index + 1); return currentFun(next); // 尾遞歸 } dispose(0);}

    總結(jié)

    以上是生活随笔為你收集整理的mysql建表的auto_increment_koa2+koa+mysql快速搭建nodejs服务器的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。