1. 程式人生 > >koa2系列教程:koa2路由控制中介軟體

koa2系列教程:koa2路由控制中介軟體

koa2系列教程,持續更新

這篇我們來使用一個koa-router, 控制一下路由

本篇的版本:注意版本哦

目錄結構:

image.png

1.編輯index.js

const Koa = require('koa')
const Router =  require('koa-router')
const app = new Koa()


// 子路由1
const home = new Router()

home.get('/', async (ctx) => {
    ctx.body = "home pages"
})


// 子路由2
const page = new Router()

page.get('/404', async (ctx) => {
    ctx.body = '404 pages'
})


const login = new Router()

login.get('/', async (ctx) => {
    ctx.body = 'login pages'
})

// 裝載所有子路由
let router = new Router()
router.use('/', home.routes(), home.allowedMethods())
router.use('/page', page.routes(), page.allowedMethods())
router.use('/login', login.routes(), login.allowedMethods())

// 載入路由中介軟體
app.use(router.routes()).use(router.allowedMethods())



app.listen(3000, () => {
    console.log('localhost:3000')
})

2.啟動服務,開啟瀏覽器

node index.js

訪問:localhost:3000, localhost;3000/login , localhost:3000/page/404

都是可以看的到結果的

image.png

關於koa-router其他API

router
  .get('/', (ctx, next) => {
    ctx.body = 'Hello World!';
  })
  .post('/users', (ctx, next) => {
    // ...
  })
  .put('/users/:id', (ctx, next) => {
    // ...
  })
  .del('/users/:id', (ctx, next) => {
    // ...
  })
  .all('/users/:id', (ctx, next) => {
    // ...
  });

後記

關於koa相關的路由控制中介軟體有很多,就看自己的選擇了

--

首發於微信公眾號:node前端

不妨關注一下