项目地址:
1. 创建项目
- 创建目录 koa-test
- npm init 创建 package.json,然后执行 npm install
- 通过 npm install koa 安装 koa 模块
- 通过 npm install supervisor 安装supervisor模块, 用于node热启动
- 在根目录下中新建 koa.js 文件,作为入口文件, 内容如下:
const Koa = require('koa'); // Koa 为一个classconst 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)})
- 配置 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" }}
- 启动项目, 打开 即可
$ npm run serve
打开页面后,显示 hello koa2
2. 根据请求路径显示不同页面
更改 koa.js
const Koa = require('koa'); // Koa 为一个classconst 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 Go Index Page'; } else { ctx.response.body = 'this is index page'; }});app.listen(3333, () => { console.log('This server is running at http://localhost:' + 3333)})
访问: 显示:this is about page Go Index Page
3. koa-router 路由管理模块的使用
koa-router 是一个处理路由的中间件
$ npm i koa-router
修改koa.js
const Koa = require('koa'); // Koa 为一个classconst Router = require('koa-router') // koa 路由中间件const app = new Koa();const router = new Router(); // 实例化路由// 添加urlrouter.get('/hello/:name', async (ctx, next) => { var name = ctx.params.name; // 获取请求参数 ctx.response.body = `Hello, ${name}!
`;});router.get('/', async (ctx, next) => { ctx.response.body = 'Index
';});app.use(router.routes());app.listen(3333, () => { console.log('This server is running at http://localhost:' + 3333)})
也可给路由统一加个前缀:
const router = new Router({ prefix: '/api'});
然后访问 即可,例如:
4. post 请求
koa2 需要使用 koa-bodyparser 中间件来处理post请求
$ npm i koa-bodyparser
修改 koa.js
const Koa = require('koa'); // Koa 为一个classconst 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 = ``;});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 = `表单
Hello, ${name}!
`;});app.use(router.routes());app.listen(3333, () => { console.log('This server is running at http://localhost:' + 3333)})参考: