koa 自學(xué)入門

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);

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末备绽,一起剝皮案震驚了整個濱河市轴咱,隨后出現(xiàn)的幾起案子湖苞,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 218,284評論 6 506
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件支竹,死亡現(xiàn)場離奇詭異眷细,居然都是意外死亡,警方通過查閱死者的電腦和手機格粪,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,115評論 3 395
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來氛改,“玉大人帐萎,你說我怎么就攤上這事∈ぢ保” “怎么了疆导?”我有些...
    開封第一講書人閱讀 164,614評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長葛躏。 經(jīng)常有香客問我澈段,道長,這世上最難降的妖魔是什么舰攒? 我笑而不...
    開封第一講書人閱讀 58,671評論 1 293
  • 正文 為了忘掉前任败富,我火速辦了婚禮,結(jié)果婚禮上摩窃,老公的妹妹穿的比我還像新娘囤耳。我一直安慰自己,他們只是感情好偶芍,可當(dāng)我...
    茶點故事閱讀 67,699評論 6 392
  • 文/花漫 我一把揭開白布充择。 她就那樣靜靜地躺著,像睡著了一般匪蟀。 火紅的嫁衣襯著肌膚如雪椎麦。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,562評論 1 305
  • 那天材彪,我揣著相機與錄音观挎,去河邊找鬼。 笑死段化,一個胖子當(dāng)著我的面吹牛嘁捷,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播显熏,決...
    沈念sama閱讀 40,309評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼雄嚣,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起缓升,我...
    開封第一講書人閱讀 39,223評論 0 276
  • 序言:老撾萬榮一對情侶失蹤鼓鲁,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后港谊,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體骇吭,經(jīng)...
    沈念sama閱讀 45,668評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,859評論 3 336
  • 正文 我和宋清朗相戀三年歧寺,在試婚紗的時候發(fā)現(xiàn)自己被綠了燥狰。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,981評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡斜筐,死狀恐怖碾局,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情奴艾,我是刑警寧澤,帶...
    沈念sama閱讀 35,705評論 5 347
  • 正文 年R本政府宣布内斯,位于F島的核電站蕴潦,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏俘闯。R本人自食惡果不足惜潭苞,卻給世界環(huán)境...
    茶點故事閱讀 41,310評論 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望真朗。 院中可真熱鬧此疹,春花似錦、人聲如沸遮婶。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,904評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽旗扑。三九已至蹦骑,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間臀防,已是汗流浹背眠菇。 一陣腳步聲響...
    開封第一講書人閱讀 33,023評論 1 270
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留袱衷,地道東北人捎废。 一個月前我還...
    沈念sama閱讀 48,146評論 3 370
  • 正文 我出身青樓,卻偏偏與公主長得像致燥,于是被迫代替她去往敵國和親登疗。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,933評論 2 355

推薦閱讀更多精彩內(nèi)容