Anything0 2019-11-05
v1 generator
v2 过渡版 generator&async
v3 async/await
koa
koa不带路由 因此得cnpm i koa-router -D
const koa = require(‘koa‘); const Router = require(‘koa-router‘); let server = new koa(); server.listen(8520,()=>{console.log(‘success‘);}); //普通路由 let router = new Router(); router.get(‘/a‘, async ctx=>{ //ctx:上下文对象 ctx.body=‘aaa‘; ctx.body+=‘bbb‘; console.log(ctx.body); }) //把router怼给server才能生效 server.use(router.routes());
//1.嵌套路由: /user /company /person /admin /news /sport /woman /man /car ...
const Router = require(‘koa-router‘); let router = new Router(); router.get(‘/‘,async ctx=>{ ctx.body=‘用户‘; }) router.use(‘/company‘,require(‘./company‘)) router.use(‘/admin‘,require(‘./admin‘)) module.exports=router.routes();
const Router = require(‘koa-router‘); let router = new Router(); router.get(‘/a‘,async ctx=>{ ctx.body=‘管理员的a‘; }) module.exports=router.routes();
const Router = require(‘koa-router‘); let router = new Router(); router.get(‘/a‘,async ctx=>{ ctx.body=‘企业的a‘; }); module.exports=router.routes();
let router = new Router(); router.use(‘/user‘,require(‘./routers/user‘)); server.use(router.routes());
运行node server.js,在浏览器输入"localhost:8520/user/admin/a",页面上则显示"管理员的a";
输入"localhost:8520/user/company/a",页面上则显示"企业的a"。
//2.参数: http://localhost:8520/news/12 http://localhost:8520/news/123/889 http://localhost:8520/news/123/555/146 quretion1: 用?id=xxx传参和/:id的区别 urlencoded http://aaa.com/user?a=12&b=5 params http://aaa.com/user/12/5 urlencoded params 顺序灵活 顺序是死的 可以省略 不可省略的 不利于SEO 利于SEO(因为地址是静态的)
const Koa = require(‘koa‘); const Router = require(‘koa-router‘); let server = new Koa(); server.listen(8520); let router = new Router(); router.get(‘/news/:id‘,async ctx=>{ console.log(ctx.params); let {id} = ctx.params ctx.body=`新闻${id}`; }); router.get(‘/news/:id/:id2‘,async ctx=>{ console.log(ctx.params); let {id,id2} = ctx.params ctx.body=`新闻${id}_${id2}`; }); router.get(‘/news/:id/:id2/:id3‘,async ctx=>{ console.log(ctx.params); let {id,id2,id3} = ctx.params ctx.body=`新闻${id}_${id2}_${id3}`; }); server.use(router.routes());
const Koa = require(‘koa‘); const Router = require(‘koa-router‘); let server = new Koa(); server.listen(8520,()=>{console.log(‘success‘);}); let router = new Router(); router.get(‘/news/‘,async ctx=>{ console.log(ctx.query); let {id} = ctx.query; }); server.use(router.routes());
熟悉ctx对象 server.context:相当于ctx的prototype 所以server.context适合放全局的东西 ctx.request ctx.response 信息: ctx.method 请求方法 ctx.url 请求地址 ctx.path 请求路径 ctx.query get数据 ctx.ip 客户端ip ctx.headers 请求头
比较方便的报错方法: ctx.throw //报错并且退出 eg: if(!ctx.query.user || !ctx.query.pass){ ctx.throw(400,‘user and password is required‘) }else{ ctx.body=‘成功‘; } ctx.assert() //断言测试 ctx.assert(条件,code,msg)==if(!条件)ctx.throw eg: ctx.assert(ctx.query.user,400,‘username is required‘)