一、创键项目
1.创建目录 koa2
2.npm init 创建 package.json,然后执行 npm install
3.通过 npm install koa 安装 koa 模块
4.通过 npm install supervisor 安装supervisor模块, 用于node热启动
5.在根目录下中新建 index.js 文件,作为入口文件, 内容如下:
const Koa = require('koa'); // Koa 为一个class const app = new Koa(); app.use(async (ctx, next) => { await next(); ctx.response.body = 'Hello, koa2!'; }); app.listen(9527, () => { console.log('This server is running at http://localhost:' + 9527) })
6.配置package
{ "name": "koa", "version": "1.0.0", "description": "", "main": "koa.js", "scripts": { "serve": "supervisor koa.js" }, "author": "", "license": "ISC", "dependencies": { "koa": "^2.7.0", "supervisor": "^0.12.0" } }
7 . 启动
npm run serve
二、路由配置
cnpm i koa-router const router = new Router(); // 实例化路由 router.get('/', async (ctx, next) => { ctx.response.body = '<h5>好家伙</h5>'; }); app.use(router.routes());
路由参数
//请求地址 www.*****/sss"htmlcode">const bodyParser = require('koa-bodyparser'); app.use(bodyParser()); router.post('/login', async (ctx, next) => { let name = ctx.request.body.name; let password = ctx.request.body.password; console.log(name, password); ctx.response.body = `<h4>好家伙, ${name}!</h4>`; });get
router.get('/', async (ctx, next) => { ctx.response.body = '<h4>好家伙</h4>' });四、html模板
1、好处
使用html模板,将html从js中分离出去,有助于项目开发和管理。而且,html模板在koa2中,必须通过中间件来实现。
2、koa-views + nunjucks实现html模板
nunjucks.configure(resolve(__dirname, 'views'), { autoescape: true }); app.use(views(__dirname + '/views', { map: { html: 'nunjucks' } }));五、操作静态资源
1、静态资源在开发中的地位
静态资源环境在服务端是十分常用的一种服务,在后台开发中不仅有需要代码处理的业务逻辑请求,也会有很多的静态资源请求。比如请求js,css,jpg,png这些静态资源请求。也非常的多,有些时候还会访问静态资源路径。
2、koa-static-cache实现静态资源操作
app.use( staticCache(resolve("dist"), { maxAge: 365 * 24 * 60 * 60 }) )六、进阶
1、结构
入口文件(index.js)
const Koa = require('koa') const bodyParser = require('koa-bodyparser'); const staticCache = require('koa-static-cache'); const views = require('koa-views') const {resolve} = require('path') const R = require('ramda') const MIDDLEWARES = ['router'] //中间件配置文件 const nunjucks = require('nunjucks') const logsUtil = require('../utils/logs.js'); //中间件导入 路由导入 const useMiddlewares = (app) => { R.map( R.compose( R.forEachObjIndexed( initWith => initWith(app) ), require, name => resolve(__dirname, `./middlewares/${name}`) ) )(MIDDLEWARES) } ;(async () => { const app = new Koa(); // view engine setup nunjucks.configure(resolve(__dirname, 'views'), { autoescape: true }); //views with nunjucks app.use(views(__dirname + '/views', { map: { html: 'nunjucks' } })); app.use(bodyParser()); app.use(logsUtil.accessInfo()); //访问日志 //静态资源配置缓存 app.use( staticCache(resolve("dist"), { maxAge: 365 * 24 * 60 * 60 }) ) app.on('error', err => { }); app.use(async (ctx,next) => { await next() if(parseInt(ctx.status) === 404){ ctx.response.redirect("/404") } }); await useMiddlewares(app) //导入中间件 app.listen(9527,() => { console.log('Server running on port %d', 9527); }) })()2、路由中间件封装
1.新建middlewares文件夹 在下面新建router.js
2.新建lib文件夹 在下面新建decorator.js
3.新建routes下面新建views.js
router.js
const { Route } = require('../lib/decorator') const { resolve } = require('path') export const router = app => { const apiPath = resolve(__dirname, '../routes') const router = new Route(app, apiPath); router.init() }decorator.js
const Router = require('koa-router') const { resolve } = require('path') const _ = require('lodash') const glob = require('glob') const R = require('ramda') const symbolPrefix = Symbol('prefix') const routerMap = new Map() const isArray = c => _.isArray(c) "htmlcode">const { controller, get } = require('../lib/decorator') @controller('') export class viewController { @get('/') async home(ctx, next) { await ctx.render('index', { }) } @get('/service') async enter(ctx, next) { await ctx.render('service', { title: '', }) } @get('/404') async pageNUll(ctx, next) { await ctx.render('404', { title: ' ', }) } }3、日志文件
cnpm i koa-log4 config/logs.jsvar path = require('path'); //日志根目录 var baseLogPath = path.resolve(__dirname, '../logs') /*报错输出日志*/ //错误日志目录、文件名、输出完整路径 var errorPath = "/error"; var errorFileName = "error"; var errorLogPath = baseLogPath + errorPath + "/" + errorFileName; /*请求数据得到响应时输出响应日志*/ //响应日志目录、文件名、输出完整路径 var responsePath = "/response"; var responseFileName = "response"; var responseLogPath = baseLogPath + responsePath + "/" + responseFileName; /*操作数据库进行增删改等敏感操作记录日志*/ //操作日志目录、文件名、输出完整路径 var handlePath = "/handle"; var handleFileName = "handle"; var handleLogPath = baseLogPath + handlePath + "/" + handleFileName; /*访问级别日志*/ var accessPath = "/access" var accessFileName = "access"; var accessLogPath = baseLogPath + accessPath + "/" + accessFileName; /*访问级别日志*/ var reqPath = "/req" var reqFileName = "req"; var reqLogPath = baseLogPath + reqPath + "/" + reqFileName; module.exports = { //日志格式等设置 appenders: { "rule-console": {"type": "console"}, "errorLogger": { "type": "dateFile", "filename": errorLogPath, "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true, "encoding": "utf-8", "path": errorPath }, "resLogger": { "type": "dateFile", "filename": responseLogPath, "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true, "encoding": "utf-8", // "maxLogSize": 204800, // "numBackups": 3, "path": responsePath }, "handleLogger": { "type": "dateFile", "filename": handleLogPath,//生成文件路径和文件名 "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true, "encoding": "utf-8", // "maxLogSize": 204800, // "numBackups": 3, "path": handlePath }, "accessLogger": { "type": "dateFile", "filename": accessLogPath, "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true, "encoding": "utf-8", // "maxLogSize": 204800, // "numBackups": 3, "path": accessPath }, "reqLogger": { "type": "dateFile", "filename": reqLogPath, "pattern": "-yyyy-MM-dd.log", "alwaysIncludePattern": true, "encoding": "utf-8", // "maxLogSize": 204800, // "numBackups": 3, "path": reqPath }, }, //供外部调用的名称和对应设置定义 categories: { "default": {"appenders": ["rule-console"], "level": "all"}, "resLogger": {"appenders": ["resLogger"], "level": "info"}, "errorLogger": {"appenders": ["errorLogger"], "level": "error"}, "handleLogger": {"appenders": ["handleLogger"], "level": "all"}, "accessLogger": {"appenders": ["accessLogger"], "level": "all"}, "reqLogger": {"appenders": ["reqLogger"], "level": "error"} }, "baseLogPath": baseLogPath }log.js
var log4js = require('koa-log4'); var logsConfig = require('../config/logs.js'); //加载配置文件 log4js.configure(logsConfig); //调用预先定义的日志名称 var resLogger = log4js.getLogger("resLogger"); var errorLogger = log4js.getLogger("errorLogger"); var handleLogger = log4js.getLogger("handleLogger"); var reqLogger = log4js.getLogger("reqLogger"); var consoleLogger = log4js.getLogger(); exports.accessInfo = () => log4js.koaLogger(log4js.getLogger('accessLogger'));//访问日志 exports.logInfo = (data) => {consoleLogger.info(data)} ............. .............关于pm2自动部署 webpack打包 以及数据库后续有时间更新
欢迎干饭人一起推动优化
最后附上工具人地址:https://gitee.com/angry2bird/node-koa
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线
暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。
艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。
《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。
更新日志
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]