项目地址: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. mv,rm等命令出现unrecognized option提示的解决方法

    出现这个提示,一般是由于命令操作的文件名最前面有"--"字符, 让命令误以为是--开头的长选项 解决: 命令后加上"--", shell把 -- 之后的参数当做 ...

  2. puppeteer入门

    转自: https://www.jianshu.com/p/a89d8d6c007b 作者: ppCode puppeteer新手入门(chromium下载跳坑) ppCode 关注 2017.12. ...

  3. 超简单,Centos7 安装 rabbitMQ

    首先声明,本人是Linux新手一枚.经历了在阿里云Centos上部署rabbitMQ与重装的痛苦经历,后多方查找终于找到了简单方法.Linux高人来说请跳过本篇文章,新手可以试试. 1.设置Cento ...

  4. CENTOS7 SYSTEMD SERVICE 将自己的程序放入自动启动的系统服务

    1. 进入文件夹cd /usr/lib/systemd/system 2. 创建文件somed.service 3. 输入内容.如果是监控类程序,需要输入Type=forking[Unit]Descr ...

  5. redis的一命令

    参考http://redisdoc.com/ 参考http://redis.io/commands 连接操作相关的命令 默认直接连接  远程连接-h 192.168.1.20 -p 6379 ping ...

  6. log4Net辅助类

    public class Log { private ILog logger; public Log(ILog log) { this.logger = log; } public void Debu ...

  7. kettle用mysql创建资源库执行sql代码报错

    一.原因:  sql语句里边使用 'Y' 'N'  给boolean类型的赋值产生sql失败    二.解决方法:将insert语句中‘Y’或‘N’ 改成TRUE或FALSE即可,共两张表3个地方  ...

  8. IDEA 如何查看一个类里面的所有方法

    快捷键:Alt+7

  9. git 一些基本的命令操作总结

    配置远程仓库:git remote add test http://xxxx/tool/device_management.git test为远程仓库别名克隆远程仓库到本地:git clone htt ...

  10. January 26th, 2018 Week 04th Friday

    A great forest is set on fire by a small spark. 最小的火能点着最大的树林. It is just a spark, but it is enough t ...