node koa2 ssr项目搭建的方法步骤
一、创键项目
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?from=1 router.get('/hello/:name', async (ctx, next) => { var name = ctx.params.name; // 获取请求参数 sss var from = ctx.query.from; // 1 ctx.response.body = `<h5>好家伙, ${name}!</h5>`; });
三、请求
post
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) ? c : [c] export class route { constructor (app, apipath) { this.app = app this.apipath = apipath this.router = new router() } init () { glob.sync(resolve(this.apipath, './**/*.js')).foreach(require) for (let [conf, controller] of routermap) { const controllers = isarray(controller) let prefixpath = conf.target[symbolprefix] if (prefixpath) prefixpath = normalizepath(prefixpath) const routerpath = prefixpath + conf.path this.router[conf.method](routerpath, ...controllers) } this.app.use(this.router.routes()) this.app.use(this.router.allowedmethods()) } } const normalizepath = path => path.startswith('/') ? path : `/${path}` const router = conf => (target, key, descriptor) => { conf.path = normalizepath(conf.path) routermap.set({ target: target, ...conf }, target[key]) } export const controller = path => target => (target.prototype[symbolprefix] = path) export const get = path => router({ method: 'get', path: path }) export const post = path => router({ method: 'post', path: path }) export const put = path => router({ method: 'put', path: path }) export const del = path => router({ method: 'delete', path: path }) export const use = path => router({ method: 'use', path: path }) export const all = path => router({ method: 'all', path: path })
view.js
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打包 以及数据库后续有时间更新
欢迎干饭人一起推动优化
最后附上工具人地址:
到此这篇关于node koa2 ssr项目搭建的方法步骤的文章就介绍到这了,更多相关node koa2 ssr项目搭建内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: 力扣 62. 不同路径
下一篇: PHP生成随机密码4种方法及性能对比