项目地址: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. Android--清除默认桌面设置和设置默认桌面(转)

    http://blog.csdn.net/chaozhung_no_l/article/details/49929177 转自这位大神的博客,感谢这位大神,帮了大忙,谢谢!!

  2. 针对需要使用T3协议的Weblogic2628漏洞解决方案

    针对需要使用T3协议的Weblogic2628漏洞解决方案 前几天用户的服务器中检查到了Weblogic2628l漏洞,并且打过Oracle官方补丁后还是能检测到. 针对此问题,去网上查找了一些资料. ...

  3. [HDFS_add_3] HDFS 机架感知

    0. 说明  HDFS 副本存放策略 && 配置机架感知 1. HDFS 的副本存放策略 HDFS 的副本存放策略是将一个副本存放在本地机架节点上,另外两个副本放在不同机架的不同节点上 ...

  4. 转载------------C函数之memcpy()函数用法

    转载于http://blog.csdn.net/tigerjibo/article/details/6841531 函数原型 void *memcpy(void*dest, const void *s ...

  5. if 嵌套if 的先后顺序的区别 (自测)

    # 验证 verify very good! # username = input("请输入用户名").capitalize()# password = input("请 ...

  6. Deepin系统安装mysql教程及相关操作

    Deepin系统安装mysql教程及相关操作 1.安装MySQL sudo apt-get install mysql-server,期间需要输入两次密码,root账户的密码. sudo apt-ge ...

  7. Linux Java 环境配置及内置tomcat部署

    tar zxvf jdk-8u101-linux-x64.tar.gz vi /etc/profile JAVA_HOME=/home/puma/jdk1.8.0_111JAVA_BIN=/home/ ...

  8. 433 模块 ARDUINO测试

    实验硬件 发射端 Arduino + 433超外差发射机     高,低电平和悬空三种模式切换  由简单的官方库修改 /* This is a minimal sketch without using ...

  9. Click to add to Favorites Troubleshooting: High Version Count Issues (Doc ID 296377.1)

    Copyright (c) 2018, Oracle. All rights reserved. Oracle Confidential. Click to add to Favorites Trou ...

  10. Linux安装solr

    solr官网下载地址为:http://mirror.bit.edu.cn/apache/lucene/solr/ 以7.6.0版本作为实践 1.下载 wget http://mirror.bit.ed ...