koa2入门(2) koa-router 路由处理
项目地址:https://github.com/caochangkui/demo/tree/koa-test
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 为一个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)
})
- 配置 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"
}
}
- 启动项目, 打开 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)
})