This is the first day of my participation in Gwen Challenge
I. Key creation project
-
Create the directory koa2
-
NPM init creates package.json and then executes NPM install
-
Install the KOA module by using NPM Install koa
-
NPM Install Supervisor Installs the Supervisor module for hot startup of nodes
-
Create an index.js file in the root directory as an entry file with the following contents:
const Koa = require('koa'); // Koa is a 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) })Copy the code
6. The configuration package
{" name ":" koa ", "version" : "1.0.0", "description" : ""," main ":" koa. Js ", "scripts" : {" serve ": "The supervisor koa. Js"}, "author" : ""," license ":" ISC ", "dependencies" : {" koa ":" ^ 2.7.0 ", "supervisor" : "^ 0.12.0"}}Copy the code
7. Start
npm run serve
Copy the code
2. Route configuration
cnpm i koa-router const router = new Router(); Router.get ('/', async (CTX, next) => {ctx.response.body = '<h5> Nice guy </h5>'; }); app.use(router.routes());Copy the code
Routing parameters
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>`; });Copy the code
Third, the request
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>`; });Copy the code
get
The router. The get ('/', async (CTX, next) = > {CTX. Response. Body = '< h4 > d < / h4 >'});Copy the code
HTML template
1, good
Using HTML templates to separate HTML from JS helps in project development and management. Also, HTML templates are in KOA2 and must be implemented through middleware.
2, Koa-views + Nunjucks HTML template implementation
nunjucks.configure(resolve(__dirname, 'views'), { autoescape: true });
app.use(views(__dirname + '/views', {
map: { html: 'nunjucks' }
}));
Copy the code
5. Operate static resources
1. The status of static resources in development
Static resource environment is a very common service in the server side. In the background development, there are not only business logic requests that need to be processed by code, but also a lot of static resource requests. Such as request JS, CSS, JPG, PNG static resource requests. A lot, sometimes accessing static resource paths.
2. Koa-static-cache implements static resource operations
app.use(
staticCache(resolve("dist"), {
maxAge: 365 * 24 * 60 * 60
})
)
Copy the code
Six, advanced
1, structure,
Write route with decorator
1. Rely on the installation
2. Configuration. Babelrc
{
"presets": ['react', 'stage-0','env'],
"plugins": [
"transform-runtime",
"transform-decorators-legacy",
"transform-class-properties"
]
}
Copy the code
3.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 })Copy the code
4.routes 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: ' ', }) } }Copy the code
3. Log files
cnpm i koa-log4 config/logs.jsvar path = require('path'); Var baseLogPath = path.resolve(__dirname, '.. Var errorPath = "/error"; /logs') /* errorPath = "/error"; var errorFileName = "error"; var errorLogPath = baseLogPath + errorPath + "/" + errorFileName; Var responsePath = "/response"; var responseFileName = "response"; var responseLogPath = baseLogPath + responsePath + "/" + responseFileName; /* Log sensitive operations such as adding, deleting, or modifying the database */ // Log directory, file name, and output path var handlePath = "/handle"; var handleFileName = "handle"; var handleLogPath = baseLogPath + handlePath + "/" + handleFileName; /* Access level log */ var accessPath = "/access" var accessFileName = "access"; var accessLogPath = baseLogPath + accessPath + "/" + accessFileName; /* Access level log */ var reqPath = "/req" var reqFileName = "req"; var reqLogPath = baseLogPath + reqPath + "/" + reqFileName; Module. exports = {// set 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, "-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": Categories: {" default": {"appenders": ["rule-console"], "level": {"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'); Configure (logsConfig); // Call the pre-defined log name 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')); / / access log exports. LogInfo = (data) = > {consoleLogger. The info (data)}... .Copy the code
3. Start the start.js file
require('babel-core/register')()
require('babel-polyfill')
require('./server/index.js')
Copy the code
cnpm i
npm start
About pM2 automatic deployment webpack packaging and the database will have time to update later
Welcome to promote the optimization together
Finally, attach the address of the tool maker: gitee.com/angry2bird/…