用Koa.js,离不开这十个中间件
koa-router文档地址 https://www.npmjs.com/package/koa-router github:https://github.com/ZijianHe/koa-router 详情链接:https://blog.csdn.net/mjzhang1993/article/details/78752314/
安装koa cnpm install koa --save
安装koa-router cnpm install koa-router --save
使用koa-router :
-
路由导航
-
get请求获取参数 (ctx.query)
-
动态路由及其获取参数(/product/:id ctx.params.id)
//引入 koa模块
var Koa=require('koa');
var router = require('koa-router')(); /*引入是实例化路由** 推荐*/
//实例化
var app=new Koa();
router.get('/',async (ctx)=>{
ctx.body="首页";
})
app.use(router.routes()); /*启动路由*/
app.use(router.allowedMethods());
/*
* router.allowedMethods()作用: 这是官方文档的推荐用法,我们可以
* 看到 router.allowedMethods()用在了路由匹配 router.routes()之后,所以在当所有
* 路由中间件最后调用.此时根据 ctx.status 设置 response 响应头
*
*/
app.listen(3000);
get请求获取参数
/*在 koa2 中 GET 传值通过 request 接收,但是接收的方法有两种:query 和 querystring。 query:返回的是格式化好的参数对象。 querystring:返回的是请求字符串。*/ //获取get传值 //http://localhost:3000/newscontent?aid=123 router.get('/newscontent',async (ctx)=>{ //从ctx中读取get传值 console.log(ctx.query); //{ aid: '123' } 获取的是对象 用的最多的方式 **推荐 console.log(ctx.querystring); //aid=123&name=zhangsan 获取的是一个字符串 console.log(ctx.url); //获取url地址 //ctx里面的request里面获取get传值 console.log(ctx.request.url); console.log(ctx.request.query); //{ aid: '123', name: 'zhangsan' } 对象 console.log(ctx.request.querystring); //aid=123&name=zhangsan })
动态路由
//请求方式 http://域名/product/123
router.get('/product/:aid',async (ctx)=>{
console.log(ctx.params); //{ aid: '123' } //获取动态路由的数据
ctx.body='这是商品页面';
});
router 的 HTTP 动词方法 get|put|post|patch|delete|del|all
router.all()
方法用来匹配所有 HTTP 动词
router
.all('/*', (ctx, next) => {
ctx.body = ctx._matchedRoute + ' all
'; // ctx._matchedRoute 获得匹配的 url
next();
})
.get('/admin', (ctx, next) => {
ctx.body += ctx._matchedRoute + ' get admin
';
next();
})
.post('/admin', (ctx, next) => {
ctx.body += ctx._matchedRoute + ' post admin
';
next();
})
.get('/admin/:user', (ctx, next) => {
// 通过 ctx.params 获取 url 参数
ctx.body += ctx._matchedRoute + '--' + ctx.params.user + ' get admin/user
';
next();
})
多个中间件
router.get('/admin/:user/*', (ctx, next) => {
ctx.body += ctx._matchedRoute + '--' + ctx.params.user + '
';
next();
}, (ctx, next) => {
ctx.body += ' get admin/user
';
next();
})
嵌套路由
const app = new Koa();
const router = new Router();
const admin = new Router();
admin.get('/:user/*', (ctx, next) => {
ctx.body += ctx._matchedRoute + '--' + ctx.params.user + '
';
next();
})
router.use('/admin', admin.routes(), admin.allowedMethods()); // 路由嵌套
app.use(router.routes());
app.use(router.allowedMethods());
定义路由前缀
const admin = new Router({
prefix: '/admin' // 定义路由前缀
});
admin.get('/:user/*', (ctx, next) => {
ctx.body += ctx._matchedRoute + '--' + ctx.params.user + '
';
next();
})
app.use(admin.routes());
app.use(admin.allowedMethods());