koa 自学入门

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);//设置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));//服务静态资源 访问 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可以手动触发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);//监听错误 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);

你可能感兴趣的:(koa 自学入门)