多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
## 一、路由 ###1.1 原生路由 - ctx.request.path :获取用户请求的路径,由此实现简单路由 ``` const main = ctx=>{ if( ctx.request.path ){ ctx.response.type='html' ctx.response.body='<h1>无此路径</h1>' }else{ ctx.response.body='<h1>这是首页</h1>' } } # 访问localhost:3000/hello 显示 '无此路径' ``` ### 1.2 koa-route模块 > 原生路由用起来不太方便,可以使用封装好的*koa-route*模块 1. 引入koa-route (npm i koa-route -S) 2. 创建响应 3. 设置响应路由 app.use(route.get('/',main)) ``` const route = require('koa-route') const about = ctx => { ctx.response.type = 'html' ctx.response.body = '<h1>这是另一页</h1><a href="/"> 返回首页</a> ' } const main = ctx => { ctx.response.body='<h1>这是首页</h1>' } app.use(route.get('/',main)) app.use(route.get('/about',about)) ``` ### 1.3 静态资源 > 如果网站提供静态资源(图片、字体、样式表、脚本......),为它们一个个写路由就很麻烦,也没必要。**koa-static**模块封装了这部分的请求。 ``` # 目录结构 |_ static |_ 01.jpg |_ 01.js # 01.js服务文件 const serve = require('koa-static') const Koa = require('koa') const app = new Koa() const main = serve('static') //相对路径 const main = serve(__diraname+'/static') //绝对路径 app.use(main) app.listen(3000) # 浏览器访问 localhost:3000/01.jpg ``` ### 1.4 重定向 > 服务器需要重定向(redirect)访问请求。比如,用户登陆以后,将他重定向到登陆前的页面。**ctx.response.redirect()**方法可以发出一个302跳转,将用户导向另一个路由。 - 关键字: ctx.response.redirect(path) ``` const Koa = require('koa') const app = new Koa() const route = require('koa-route') const about = ctx => { ctx.response.redirect('/') } const main = ctx => { ctx.response.body='<h1>这是首页</h1>' } app.use(route.get('/',main)) app.use(route.get('/about',about)) app.listen(3000) ```