项目地址: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 文件,作为入口文件, 内容如下:
const Koa = require('koa'); // Koa 为一个class
const app = new Koa(); app.use(async (ctx, next) => {
await next();
ctx.response.body = 'Hello, koa2!';
}); app.listen(3333, () => {
console.log('This server is running at http://localhost:' + 3333)
})
  1. 配置 package.json 文件
{
"name": "koa-test",
"version": "1.0.0",
"description": "",
"main": "koa.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"serve": "supervisor koa.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"koa": "^2.7.0",
"supervisor": "^0.12.0"
}
}
  1. 启动项目, 打开 http://localhost:3333 即可
$ npm run serve

打开页面后,显示 hello koa2

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

更改 koa.js

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

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

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

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

$ npm i koa-router

修改koa.js

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

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

const router = new Router({
prefix: '/api'
});

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

4. post 请求

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

$ npm i koa-bodyparser

修改 koa.js

const Koa = require('koa'); // Koa 为一个class
const Router = require('koa-router') // koa 路由中间件
const bodyParser = require('koa-bodyparser'); // 处理post请求,把 koa2 上下文的表单数据解析到 ctx.request.body 中
const app = new Koa();
const router = new Router(); // 实例化路由 app.use(bodyParser()) // 表单
router.get('/', async (ctx, next) => {
ctx.response.body = `<h1>表单</h1>
<form action="/login" method="post">
<p>Name: <input name="name" value="koa2"></p>
<p>Password: <input name="password" type="password"></p>
<p><input type="submit" value="Submit"></p>
</form>`;
}); router.post('/login', async (ctx, next) => {
let name = ctx.request.body.name;
let password = ctx.request.body.password; console.log(name, password); ctx.response.body = `<h4>Hello, ${name}!</h4>`;
}); app.use(router.routes()); app.listen(3333, () => {
console.log('This server is running at http://localhost:' + 3333)
})

参考: 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. 输入两个整数n和m,从数列1,2,3,……n中随意取几个数,使其和等于m

    题目:编程求解,输入两个整数n和m,从数列1,2,3,……n中随意取几个数,使其和等于m.要求将所有的可能组合列出来. 分析:分治的思想.可以把问题(m,n)拆分(m - n, n -1)和(m, n ...

  2. vs2012碰到生成时报该错误:项目中不存在目标“GatherAllFilesToPublish”

    手头一个vs2010升级到vs2012后,web项目发布到本地目录时项目报错:“该项目中不存在目标“GatherAllFilesToPublish”” 通过谷歌大神的帮助,找到了解决方法.共享之. 原 ...

  3. 【redis专题(4)】命令语法介绍之sorted_set

    有序集合可以模拟优先级队列的实现 增 zadd key score1 value1 score2 value2 .. redis 127.0.0.1:6379> zadd stu 18 lily ...

  4. 自己搭建anki同步服务器

    最近帮孩子找学习的软件,发现了anki 不过同步速度太慢,但发现可以自己搭建同步服务器 具体方法见https://github.com/dsnopek/anki-sync-server 我的安装过程如 ...

  5. 基于 node 搭建博客系统(一)

    系统分为两端,分别实现. 管理员端: 功能 :个人信息,设置,发布随笔,随笔列表,删除随笔,查找,文章 等. 技术点:Boostrap + AdminLTE; 基于nodejs 实现的express ...

  6. 洗礼灵魂,修炼python(52)--爬虫篇—【转载】爬虫工具列表

    与爬虫相关的常用模块列表. 原文出处:传送门链接 网络 通用 urllib -网络库(stdlib). requests -网络库. grab – 网络库(基于pycurl). pycurl – 网络 ...

  7. php中编码转换方法

    php里经常用到编码转换,在这记录一个常用的编码转换方法,字符串.数组.对象都可以使用,使用了递归来解决,比较普通 /* * php中编码转换 * @param $param 需要转换的数据 * @p ...

  8. Solr全文检索

    1.Solr的安装 .环境要求 jdk1.+tomcat8+solr5.5.0 .将以上的软件包上传到服务器 . 安装tomcat8(解压文件) tar -zxvf apache-tomcat-.ta ...

  9. Matplotlib:tick_params参数设置

    1.tick_params语法 参数:axis : {‘x’, ‘y’, ‘both’} Axis on which to operate; default is ‘both’.reset : boo ...

  10. D-Link DIR-600 - Authentication Bypass

    #Exploit Title: D-Link DIR-600 - Authentication Bypass (Absolute Path Traversal Attack) # CVE - http ...