const Koa = require('koa');const route = require('koa-route');const app = new Koa();const serve = require('koa-static');//koa-static package could be used to serve static assets.const compose = require('koa-compose');//koa-compose package is used to compose multi middlewares into one.const fs = require('fs');//文件管理模塊const path = require('path');const koaBody = require('koa-body');//用于獲取request里的form的信息const about = ctx => { ctx.response.type = 'html'; ctx.response.body = 'Index Page';};const main = ctx => { // ctx.response.body = 'Hello World'; const n = Number(ctx.cookies.get('view') || 0) + 1; ctx.cookies.set('view', n);//設(shè)置cookie ctx.response.body = n + ' views';};const me = (ctx, next) =>{ctx.response.type = 'html'ctx.response.body = fs.createReadStream('./demos/template.html')console.log('<<1')console.log(`${Date.now()} ${ctx.request.method} ${ctx.request.url}`)next()//中間件console.log('>>1')}// 輸出順序:<<1 2 >>1 (中間件遵守先進先出的順序)const her = (ctx, next) =>{console.log('2')next();}const pp = ctx =>{console.log('pp')ctx.response.body = 'pp'}const multiIntoOne = compose([me,her])//多個中間件組合const staticAssets = serve(path.join(__dirname));//服務(wù)靜態(tài)資源 訪問 http://127.0.0.1:3000/06.jsconst redirect = ctx => { ctx.response.redirect('/pp');//重定向 ctx.response.body = '重定向';}const netWorkError = ctx => { ctx.throw(500);//扔出500錯誤}const error404 = ctx =>{ ctx.response.status = 404; ctx.response.body = 'Page Not Found';}const handler1 = async (ctx, next) => {try { await next()}catch (err){ctx.response.status = err.statusCode || err.status || 500;ctx.response.body = {message: err.message};}}const handler = async (ctx, next) => { try { await next(); } catch (err) { ctx.response.status = err.statusCode || err.status || 500; ctx.response.type = 'html'; ctx.response.body = '
Something wrong, please contact administrator.
';? ? ctx.app.emit('error', err, ctx);? //error emit可以手動觸發(fā)error? }};const main2 = async function(ctx) {const body = ctx.request.body;if(!body.name) ctx.throw(400, '.name required');ctx.body = { name:body.name }}app.use(staticAssets)//訪問 http://127.0.0.1:3000/06.jsapp.use(route.get('/', main));app.use(route.get('/about', about));app.use(route.post('/me',me));app.use(route.get('/pp', pp));app.use(multiIntoOne);app.use(route.get('/redirect', redirect));app.on('error', (err, ctx) => {? console.error('server error', err);//監(jiān)聽錯誤 You will see server error in the command line console.});// app.use(handler1);//A error-handling middleware could be put on the top of middleware stack to catch the thrown errors.// app.use(netWorkError)//扔出500錯誤// app.use(error404)//404// app.use(koaBody());// app.use(main2);app.listen(3000);