项目地址:https://github.com/caochangkui/demo/tree/koa-test

1. 创建项目

  1. 创建目录 koa-test
  2. npm init 创建 package.json,然后执行 npm install
  3. 通过 npm install koa 安装 koa 模块
  4. 通过 npm install supervisor 安装supervisor模块, 用于node热启动
  5. 在根目录下中新建 koa.js 文件,作为入口文件, 内容如下:
  1. const Koa = require('koa'); // Koa 为一个class
  2. const app = new Koa();
  3. app.use(async (ctx, next) => {
  4. await next();
  5. ctx.response.body = 'Hello, koa2!';
  6. });
  7. app.listen(3333, () => {
  8. console.log('This server is running at http://localhost:' + 3333)
  9. })
  1. 配置 package.json 文件
  1. {
  2. "name": "koa-test",
  3. "version": "1.0.0",
  4. "description": "",
  5. "main": "koa.js",
  6. "scripts": {
  7. "test": "echo \"Error: no test specified\" && exit 1",
  8. "serve": "supervisor koa.js"
  9. },
  10. "author": "",
  11. "license": "ISC",
  12. "dependencies": {
  13. "koa": "^2.7.0",
  14. "supervisor": "^0.12.0"
  15. }
  16. }
  1. 启动项目, 打开 http://localhost:3333 即可
  1. $ npm run serve

打开页面后,显示 hello koa2

2. 根据请求路径显示不同页面

更改 koa.js

  1. const Koa = require('koa'); // Koa 为一个class
  2. const app = new Koa();
  3. app.use(async (ctx, next) => {
  4. await next();
  5. if (ctx.request.path == '/about') {
  6. ctx.response.type = 'html'; // 指定返回类型为 html 类型
  7. ctx.response.body = 'this is about page <a href="/">Go Index Page</a>';
  8. } else {
  9. ctx.response.body = 'this is index page';
  10. }
  11. });
  12. app.listen(3333, () => {
  13. console.log('This server is running at http://localhost:' + 3333)
  14. })

访问:http://localhost:3333/about 显示:this is about page Go Index Page

3. koa-router 路由管理模块的使用

koa-router 是一个处理路由的中间件

  1. $ npm i koa-router

修改koa.js

  1. const Koa = require('koa'); // Koa 为一个class
  2. const Router = require('koa-router') // koa 路由中间件
  3. const app = new Koa();
  4. const router = new Router(); // 实例化路由
  5. // 添加url
  6. router.get('/hello/:name', async (ctx, next) => {
  7. var name = ctx.params.name; // 获取请求参数
  8. ctx.response.body = `<h5>Hello, ${name}!</h5>`;
  9. });
  10. router.get('/', async (ctx, next) => {
  11. ctx.response.body = '<h5>Index</h5>';
  12. });
  13. app.use(router.routes());
  14. app.listen(3333, () => {
  15. console.log('This server is running at http://localhost:' + 3333)
  16. })

也可给路由统一加个前缀:

  1. const router = new Router({
  2. prefix: '/api'
  3. });

然后访问 http://localhost:3333/api 即可,例如:http://localhost:3333/api/hello/koa2

4. post 请求

koa2 需要使用 koa-bodyparser 中间件来处理post请求

  1. $ npm i koa-bodyparser

修改 koa.js

  1. const Koa = require('koa'); // Koa 为一个class
  2. const Router = require('koa-router') // koa 路由中间件
  3. const bodyParser = require('koa-bodyparser'); // 处理post请求,把 koa2 上下文的表单数据解析到 ctx.request.body 中
  4. const app = new Koa();
  5. const router = new Router(); // 实例化路由
  6. app.use(bodyParser())
  7. // 表单
  8. router.get('/', async (ctx, next) => {
  9. ctx.response.body = `<h1>表单</h1>
  10. <form action="/login" method="post">
  11. <p>Name: <input name="name" value="koa2"></p>
  12. <p>Password: <input name="password" type="password"></p>
  13. <p><input type="submit" value="Submit"></p>
  14. </form>`;
  15. });
  16. router.post('/login', async (ctx, next) => {
  17. let name = ctx.request.body.name;
  18. let password = ctx.request.body.password;
  19. console.log(name, password);
  20. ctx.response.body = `<h4>Hello, ${name}!</h4>`;
  21. });
  22. app.use(router.routes());
  23. app.listen(3333, () => {
  24. console.log('This server is running at http://localhost:' + 3333)
  25. })

参考: https://www.liaoxuefeng.com/wiki/001434446689867b27157e896e74d51a89c25cc8b43bdb3000/001471087582981d6c0ea265bf241b59a04fa6f61d767f6000

koa2入门(2) koa-router 路由处理的更多相关文章

  1. koa2入门--03.koa中间件以及中间件执行流程

    //中间件:先访问app的中间件的执行顺序类似嵌套函数,由外到内,再由内到外 //应用级中间件 const koa = require('koa'); var router = require('ko ...

  2. KoaHub平台基于Node.js开发的Koa router路由插件代码信息详情

    koa-router Router middleware for koa. Provides RESTful resource routing. koa-router       Router mid ...

  3. koa2入门--02.koa2路由

    首先输入在项目文件下使用cmd,输入 npm install koa-router --save const koa = require('koa');//引入koa const Router = r ...

  4. Angular 从入坑到挖坑 - Router 路由使用入门指北

    一.Overview Angular 入坑记录的笔记第五篇,因为一直在加班的缘故拖了有一个多月,主要是介绍在 Angular 中如何配置路由,完成重定向以及参数传递.至于路由守卫.路由懒加载等&quo ...

  5. koa2入门使用总结

    koa2的介绍 Koa 是一个新的 web 框架,由 Express 幕后的原班人马打造, 致力于成为 web 应用和 API 开发领域中的一个更小.更富有表现力.更健壮的基石. 通过利用 async ...

  6. 手写@koa/router源码

    上一篇文章我们讲了Koa的基本架构,可以看到Koa的基本架构只有中间件内核,并没有其他功能,路由功能也没有.要实现路由功能我们必须引入第三方中间件,本文要讲的路由中间件是@koa/router,这个中 ...

  7. 前端MVC Vue2学习总结(八)——Vue Router路由、Vuex状态管理、Element-UI

    一.Vue Router路由 二.Vuex状态管理 三.Element-UI Element-UI是饿了么前端团队推出的一款基于Vue.js 2.0 的桌面端UI框架,手机端有对应框架是 Mint U ...

  8. 全面解析JavaScript的Backbone.js框架中的Router路由

    这篇文章主要介绍了Backbone.js框架中的Router路由功能,Router在Backbone中相当于一个MVC框架中的Controller控制器功能,需要的朋友可以参考下. Backbone ...

  9. React初识整理(四)--React Router(路由)

    官网:https://reacttraining.com/react-router 后端路由:主要做路径和方法的匹配,从而从后台获取相应的数据 前端路由:用于路径和组件的匹配,从而实现组件的切换. 如 ...

  10. hbuilderX创建vue项目之添加router路由(前端萌新)

    作为一个刚刚接触前端不久的新人来说,熟悉了一种目录结构或者项目创建方法以后,恨不得一辈子不会变! 可是人要生活,就要工作,既然是打工,当然要满足雇佣者的要求. 今天我来说说 hbuilderX 这个开 ...

随机推荐

  1. 【Java入门提高篇】Day31 Java容器类详解(十三)TreeSet详解

    上一篇很水的介绍完了TreeMap,这一篇来看看更水的TreeSet. 本文将从以下几个角度进行展开: 1.TreeSet简介和使用栗子 2.TreeSet源码分析 本篇大约需食用10分钟,各位看官请 ...

  2. synchronized的锁问题

    有一个类A,提供了三个方法.分别是静态同步方法,非静态同步方法,含有静态代码块的方法 1 class A{ 2 public static synchronized void print1(){ 3 ...

  3. wx python 基本控件

    一.静态文本控件 wx.StaticText(parent, id, label, pos=wx.DefaultPosition,    size=wx.DefaultSize, style=0, n ...

  4. tkinter中Radiobutton单选框控件(七)

    Radiobutton控件 由于本次内容中好多知识都是之前重复解释过的,本次就不做解释了.不太清楚的内容请参考tkinter1-6节中的内容 import tkinter wuya = tkinter ...

  5. Matplotlib:可视化颜色命名分类和映射颜色分类

    Matplotlib中支持的所有颜色分类 映射颜色分类

  6. 06LaTeX学习系列之---TeXstudio的使用

    目录 目录 前言 (一)TeXstudio的认识 1.TeXstudio的安装 2.TeXstudio的优点 3.Texstudio的界面 (二)TeXstudio的编译与查看 (三)TeXstudi ...

  7. Django 项目连接数据库Mysql要安装mysqlclient驱动出错 : Failed building wheel for mysqlclient:

    1,如果直接用 CMD命令:pip install mysqlclient ,会安装出错. 2,解决问题,参考了这个博友的帖子:https://blog.csdn.net/qq_29784441/ar ...

  8. C语言变量定义与数据溢出(初学者)

    1.变量定义的一般形式为:类型说明符.变量名标识符等:例:int a,b,c;(abc为整型变量) 在书写变量定义时应注意以下几点: (1)允许在一个类型说明符后,定义多个相同类型的变量.各变量之间用 ...

  9. 协程与concurent.furtrue实现线程池与进程池

    1concurent.furtrue实现线程池与进程池 2协程 1concurent.furtrue实现线程池与进程池 实现进程池 #进程池 from concurrent.futures impor ...

  10. MongoDB 4.6.1 c++ driver 编译

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/sheismylife/article/details/25512251 这个版本号已经和之前不一样了 ...