koa(四)路由中間件

1.中間件

/**
 * 錯(cuò)誤處理中間件
 */
// 引入模塊
const Koa = require('koa');
const router = require('koa-router')(); /*引入是實(shí)例化路由 推薦*/
 
// 實(shí)例化
let app = new Koa();
 
// Koa中間件
// 匹配任何路由,如果不寫next,這個(gè)路由被匹配到了就不會(huì)繼續(xù)向下匹配
 
// www.域名.com/news
app.use(async (ctx, next) => {
  console.log('這是一個(gè)中間件01');
  next();
 
  if(ctx.status == 404) {
    ctx.status = 404;
    ctx.body = '這是一個(gè) 404 頁面';
  } else {
    console.log(ctx.url);
  }
})
 
router.get('/', async (ctx) => {
  ctx.body = '首頁';
})
 
router.get('/news', async (ctx) => {
  ctx.body = '這是一個(gè)新聞2';
})
 
router.get('/login', async (ctx) => {
  ctx.body = '登錄頁面';
})
 
app.use(router.routes());
app.use(router.allowedMethods());
/**
 * router.allowedMethods() 作用:這是官方文檔的推薦用法,我們可以
 * 看到 router.allowedMethods() 用在了路由匹配 router.routes()之后,
 * 所以在當(dāng)所有路由中間件最后調(diào)用,此時(shí)根據(jù) ctx.status 設(shè)置 response 響應(yīng)頭
 */
 
app.listen(3000);
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容