路由

作者: 阿水日记 | 来源:发表于2018-11-21 20:02 被阅读0次

一、Koa 路由

1.安装koa-router

cnpm install koa-router -S

2.一个简单的路由实例

const Koa = require('koa')
const Router = require('koa-router')
const app = new Koa()
const router = new Router()

//配置路由
router.get("/", async (ctx)=>{
    ctx.body = "<h1>首页</h1>"
}).get("/news", async (ctx)=>{
    ctx.body = "<h1>新闻页</h1>"
})

//启动路由
app.use(router.routes());
app.use(router.allowedMethods()); //可以配置也可以不配置
/* 作用: 这是官方文档的推荐用法,我们可以看到 router.allowedMethods()用在了路由匹配 router.routes()之后,
所以在当所有路由中间件最后调用.此时根据 ctx.status 设置 response 响应头*/
 

app.listen(3000) 

3.另一种推荐的写法

const Koa = require('koa')
const router = require('koa-router')()//引入并实例化路由
const app = new Koa

router.get('/',async (ctx) => {
    ctx.body = "<h1>首页</h1>"
})

router.get('/news',async (ctx) => {
    ctx.body = "<h1>新闻</h1>"
})

router.get('/products',async (ctx) => {
    ctx.body = "<h1>产品</h1>"
})

//启动路由
app.use(router.routes());
app.use(router.allowedMethods());
app.listen(3000)


二、Koa 路由 get 传值

在 koa2 中 GET 传值通过 request 接收,但是接收的方法有两种:query 和 querystring。

query:返回的是格式化好的参数对象。
querystring:返回的是请求字符串。

//获取get传值
router.get('/news',async (ctx) => {
    //1.从ctx中读取传值
    //访问:http://localhost:3000/news?id=2&catid=12
    console.log(ctx.query);//用的最多的方式 (推荐)
        //输出{ id: '2', catid: '12' }
    console.log(ctx.querystring);
        //id=2&catid=12
    console.log(ctx.url);
        ///news?id=2&catid=12

    //2.从ctx里的request
    console.log(ctx.request);
        //{method,url,header}
    console.log(ctx.request.query);
        //{ id: '2', catid: '12' }
    console.log(ctx.request.querystring);
        //id=2&catid=12
    


    ctx.body = "<h1>新闻</h1>"
})

三、Koa 动态路由

这里有点类似于vue里的路由

//动态路由 加?表示后面可以不加参数 当然也支持多个参数
router.get('/news/:aid?',async (ctx) => {
    //获取动态路由的传值
    //http://localhost:3000/news/lqs
    console.log(ctx.params)
    //{ aid: 'lqs' }


    ctx.body = "<h1>新闻</h1>"
})

相关文章

  • thinkphp5学习笔记(三)路由配置

    URL请求的执行流程 路由模式 路由注册 路由规则 路由地址 路由参数 变量规则 路由分组 别名路由 路由绑定

  • larevel 路由索引

    基本路由:路由重定向、视图路由路由参数:必选、可选、正则表达式命名路由路由组:中间件、命名空间、子域名路由、路由前...

  • laravel路由

    2 路由格式 3 路由参数 4 .路由别名 5 .路由群组

  • Vue3: 前端路由的概念和原理

    1、什么是路由 路由(英文:router)就是对应关系。路由分为两大类:① 后端路由② 前端路由 2、后端路由 后...

  • 组件化2.路由框架的设计

    路由框架原理 路由框架是为了实现组件之间的通信 路由框架维护了一个分组的路由表路由表中存放了路由地址和路由信息路由...

  • vue中的路由

    vue中4中路由包含: 1、动态路由2、嵌套路由3、编程式路由4、命名式路由 1、动态路由 2、嵌套路由 3、编程...

  • React-Router知识点

    路由的分类 页面路由 hash 路由 h5路由 react路由 react-router-dom 路由方式 h5路...

  • 路由策略

    路由策略和策略路由 什么是路由策略?路由策略和策略路由有什么区别? 如何配置路由策略? https://blog....

  • Laravel 学习笔记

    路由 文件位置: app/Http/routes.php 基础路由get/post 多请求路由 路由参数 路由别名...

  • React路由

    React路由 一、路由的形式 hash路由 : HashRouter history路由 : BrowserRo...

网友评论

      本文标题:路由

      本文链接:https://www.haomeiwen.com/subject/mrfhqqtx.html