美文网首页
koa2使用路由中间件

koa2使用路由中间件

作者: 夏夏夏夏顿天 | 来源:发表于2018-11-27 16:11 被阅读22次

这篇我们来使用一个koa-router, 控制一下路由

本篇的版本:注意版本哦

目录结构:

image.png

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

都是可以看的到结果的

image.png

关于koa-router其他API

源码地址:https://github.com/alexmingoia/koa-router

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

相关文章

  • 跟我一起学koa2之路由开发、日志处理

    路由开发 我们在前面已经熟悉了koa2的中间件,路由等。也学会了怎么去使用redis存session。下面我们就开...

  • 知识点总结

    Koa2中间件 koa(面向node.js的表达式HTTP中间件框架)、koa-router(路由中间件)、koa...

  • NodeJs koa2实现文件上传

    知识讲解 koa2框架是一个基于中间件的框架,也就是说,需要使用到的功能,比如路由(koa-router),日志(...

  • Gin-中间件-使用

    全局使用中间件 指定路由使用中间件

  • koa2使用路由中间件

    这篇我们来使用一个koa-router, 控制一下路由 本篇的版本:注意版本哦 目录结构: 1.编辑index.j...

  • Express学习

    使用中间件 Express 应用可使用如下几种中间件:* 应用级中间件* 路由级中间件* 错误处理中间...

  • koa中间件编写

    如何编写koa框架的中间价? 使用过koa2的朋友们都知道,koa2依赖的中间件不少1、koa-router2、k...

  • koa2中间件

    如何写一个koa2中间件呢?下面写一个简单的案例 创建koa2服务,新建一个文件 如何使用? 在需要使用的地方引入...

  • 2019-04-08

    Nodejs -- 使用koa2搭建数据爬虫 当前爬虫项目开发所需中间件: cheerio: 则能够对请求结果进行...

  • Asp.Net Core 第07局:路由

    总目录 前言 环境 开局 第一手:路由概述 第二手:路由中间件使用 1.注册路由中间件(RoutingMiddle...

网友评论

      本文标题:koa2使用路由中间件

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