项目地址: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. Kotlin入门(12)类的概貌与构造

    上一篇文章提到泛型函数appendString是在类外面定义,这不免使人疑惑,类里面又该怎样定义成员函数呢?为解答这个疑问,接下来的几篇文章将好好描述一下Kotlin如何操作类及其对象,本篇文章先对类 ...

  2. 怎么查找Jenkins的个人api token

    程序中可变部分解释:其中server.build_job方法传入的参数channel为分渠道构建参数,也即jenkins job的参数,这个参数随不同的日常job不同是不同的,实际编写脚本的过程中这个 ...

  3. 分享MYSQL中的各种高可用技术

    分享MYSQL中的各种高可用技术 图片和资料来源于姜承尧老师(MYSQL技术内幕作者) mysql高可用各个技术的比较 数据库的可靠指的是数据可靠 数据库可用指的是数据库服务可用 可靠的是数据:例如工 ...

  4. echars关系图

    <!DOCTYPE html> <html> <head> <meta name="viewport" content="wid ...

  5. SQL中的每一张表都必须设有主键吗

    问题描述: 公司的数据库表有时候会看到没有主键的,SQL中的每一张表都必须设有主键吗? 主键的作用: 1)保证实体的完整性: 2)加快数据库的操作速度: 3)在表中添加新记录时,数据库ACCESS会自 ...

  6. Mysql基础之 基础知识解释

    Mysql基础知识 RDBMS:关系型数据库管理系统.是将数据组织成相关的行和列的系统 存储过程:是存储在数据库中的一段声明性语句.触发器.java.php等都可以调用其存储过程.早期的mysql版本 ...

  7. linux系统日志自动切割工具----logrotate

    参考资料 :https://www.cnblogs.com/kevingrace/p/6307298.html 对于Linux系统安全来说,日志文件是极其重要的工具.不知为何,我发现很多运维同学的服务 ...

  8. ABAP 中JSON格式的转换与解析

    RT,JSON是当今十分流行的一种轻量数据格式,广泛地应用于各种数据交换场景中.本文会介绍一种比较简单的将ABAP中的数据转换为JSON格式的方法. (如果你是因为引号的问题搜索到了这篇文章,请直接拉 ...

  9. WPFのImage控件souce引入的方法总结

    1.后台代码相对路径添加(若为绝对路径,换UriKind的属性即可) BitmapImage testBitmapImage = new BitmapImage(new Uri(@"\bin ...

  10. js删除数组元素、清空数组的简单方法

    一.清空数组 ? 1 2 3 var ary = [1,2,3,4]; ary.splice(0,ary.length);//清空数组 console.log(ary); // 输出 [],空数组,即 ...