koa2系列教程,持續更新前端
這篇咱們來使用一個koa-router, 控制一下路由node
本篇的版本:注意版本哦git
目錄結構:github
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.啓動服務,打開瀏覽器segmentfault
node index.js
訪問:localhost:3000, localhost;3000/login , localhost:3000/page/404瀏覽器
都是能夠看的到結果的微信
源碼地址:https://github.com/alexmingoi...app
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相關的路由控制中間件有不少,就看本身的選擇了koa
這裏有箇中路由中間件聚集https://cnodejs.org/topic/57838dfaee5f048d54f90877async
--
首發於微信公衆號:node前端
不妨關注一下