# 旧岛后端 **Repository Path**: javafdx/back-end-of-old-island ## Basic Information - **Project Name**: 旧岛后端 - **Description**: 旧岛项目node-koa - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 1 - **Created**: 2021-06-20 - **Last Updated**: 2023-03-27 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ### npm install koa -S ### 使用router管理请求接口 npm install koa-router -save ### 断点调试F5 ### 热更新 npm i nodemon -g 全局 启动项目: nodemon app.js 开发局部环境 npm install nodemon --save-dev 创建nodemon.json 文件(设置某些文件在改变时不重启) { "restartable": "rs", "ignore": [ ".git", ".svn", "node_modules/**/node_modules" ], "verbose": true, "execMap": { "js": "node --harmony" }, "watch": [ ], "env": { "NODE_ENV": "development" }, "ext": "ejs js json" } 更改package.json文件 "start": "nodemon ./bin/www" 第二种使用npx npx nodemon index.js 不建议热更新--太占内存 ### 自动引入api包(实现路由自动注册) require-directory(实现路由自动注册) npm install require-directory -S 新建core--init.js初始化管理器InitManager const requireDirectory = require('require-directory'); // 每次都会执行whenLoadModule方法 requireDirectory(module, './api',{visit:whenLoadModule}); function whenLoadModule(){ if(obj instanceof Router) { app.use(obj.routes()); } } app.js引入 const InitManager = require('./core/init'); InitManager.initCore(app) rocess.cwd() 方法会返回 Node.js 进程的当前工作目录 ### post参数获取 获取POST请求body参数 npm install koa-bodyparser --save 注册: const parser = require('koa-bodyparser') app.use(parser()) 使用: const body = ctx.request.body 实践: 使用postman请求接口 post请求 localhost:3000/v1/3/classic/latest?param=kk Header: token:123456 query: param=kk body: { "key": "fudongxu" } ### 参数校验 自定义-LinValidator 一些校验规则 validators文件 ### 异常处理 抛出异常:throw new Error('error') 捕获: try { } catch (error) { } 异步捕获异常 async try { await } catch () { } ### 封装全局异常处理 新建文件middlewares--exception.js const catchError = async (ctx, next) => { try { await next() } catch (error) { ctx.body = '服务器有点问题,你等一下' } } module.exports = catchError 使用:throw new Error('API Exception') 用到了AOP面向切面编程 粗暴的捕获全局异常 ### 异常分类返回格式 已知异常和未知异常 if(!query) { const error = new Error('为什么错误'); error.error_code = 10001 error.status = 400 // 参数错误 error.request_url = `${ctx.method} ${ctx.path}` throw error } ### HttpException异常基类 新建core--http-exception.js class HttpException extends Error { constructor(msg='服务器异常', errorCode=1000, code=400){ super() this.errorCode = errorCode this.code = code this.msg = msg } } module.exports = { HttpException } 使用: const {HttpException} = require('../../../core/http-exception') const error = new HttpException('报错了', 10001, 400) ### 将异常类封装成全局变量 // 调用异常类 InitManager.loadHttpException(); // 将异常方法挂载到全局 static loadHttpException(){ const errors = require('./http-exception') global.errs = errors } 使用: const error = new global.errs.ParameterException(); ### 未知异常 else{ // 未知异常 ctx.body = { msg: '未知异常', error_code: 999, request: `${ctx.method} ${ctx.path}` } ctx.status = 500 } ### Lin-Validator校验 安装 validator 字符串验证器和消毒器库。 https://doc.cms.talelin.com/ https://doc.cms.talelin.com/start/koa/ npm install validator --save 安装lodash Lodash 通过降低 array、number、objects、string 等等的使用难度从而让 JavaScript 变得更简单。 Lodash 的模块化方法 非常适用于: npm install lodash --save 安装jsonwebtoken 生成token,完成用户登录、登录检测 npm install jsonwebtoken --save 遍历 array、object 和 string 对值进行操作和检测 创建符合功能的函数 新建core-->util.js -->lin-validator.js app-->validators-->validator.js ### 利用LinValidator获取参数 let id = v.get('path.id', parsed=false) // parsed=false 不需要转成Int ### 配置文件与在开发环境终端显示异常 新建config-->config.js module.exports = { // dev开发 prod生产 environment: 'dev' } ---exception.js // 判断当前环境,开发环境(将异常打印在控制台) if(global.config.environment === 'dev'){ throw error } ### 新建数据库 7yue 默认字符集utf8mb4 默认字符集规则utf8mb4_general_ci ### 引入依赖 npm install sequelize --save 新建core--db.js 将数据库信息配置在 config--config.js中 mysql2安装数据库驱动 npm install mysql2 --save ### 定义模型 新建models-->user.js const {sequelize} = require('../../core/db') const {Sequelize,Model} = require('sequelize') class User extends Model { } // 声明属性 User.init({ // 主动设置主键,默认会自动设置 id: { type:Sequelize.INTEGER, primaryKey: true, // 主键 autoIncrement: true, // 自增 }, nickname: Sequelize.STRING, email: Sequelize.STRING, password: Sequelize.STRING, openid: { type: Sequelize.STRING(64), // 64长度 unique: true, // 唯一 } }, {sequelize}) 测试app.js require('./app/models/user') 打印: Executing (default): CREATE TABLE IF NOT EXISTS `Users` (`id` INTEGER auto_increment , `nickname` VARCHAR(255), `email` VARCHAR(255), `password` VARCHAR(255), `openid` VARCHAR(64) UNIQUE, `createdAt` DATETIME NOT NULL, `updatedAt` DATETIME NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB;