您好,登錄后才能下訂單哦!
怎么快速搭建一個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 = '<h6>好家伙</h6>'; }); 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 = `<h6>好家伙, ${name}!</h6>`; });
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 = `<h5>好家伙, ${name}!</h5>`; });
get
router.get('/', async (ctx, next) => { ctx.response.body = '<h5>好家伙</h5>' });
使用html模板,將html從js中分離出去,有助于項目開發和管理。而且,html模板在koa2中,必須通過中間件來實現。
nunjucks.configure(resolve(__dirname, 'views'), { autoescape: true }); app.use(views(__dirname + '/views', { map: { html: 'nunjucks' } }));
靜態資源環境在服務端是十分常用的一種服務,在后臺開發中不僅有需要代碼處理的業務邏輯請求,也會有很多的靜態資源請求。比如請求js,css,jpg,png這些靜態資源請求。也非常的多,有些時候還會訪問靜態資源路徑。
app.use( staticCache(resolve("dist"), { maxAge: 365 * 24 * 60 * 60 }) )
入口文件(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); }) })()
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: ' ', }) } }
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)} ............. .............
關于怎么快速搭建一個node koa2 ssr項目問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。