koa2系列教程,延续更新
- koa2系列教程:koa2运用初见
- koa2系列教程:koa2处置惩罚静态文件
- koa2系列教程:koa2运用模板引擎
- koa2系列教程:koa2路由掌握中间件
- koa2系列教程:综合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前端
无妨关注一下