koa2系列教程,持續更新
這篇我們來使用一個koa-router, 控制一下路由
本篇的版本:注意版本哦
目錄結構:
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
都是可以看的到結果的
關於koa-router其他API
源碼地址:https://github.com/alexmingoi...
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相關的路由控制中間件有很多,就看自己的選擇了
這裏有箇中路由中間件彙集https://cnodejs.org/topic/57838dfaee5f048d54f90877
--
首發於微信公衆號:node前端
不妨關注一下