lixin-macbook:koa-example lixin$ npm install koa-router --save
// 引入koa
const Koa = require("koa");
// 引入koa-router
const Router = require('koa-router');
// 创建Koa实例
const app = new Koa();
// 创建Router实例
const router = new Router();
// 配置路由
// curl -X GET http://localhost:8080?name=zhgnsan
router.get('/', async (ctx, next) => {
// let query = ctx.query;
// {name : "zhgnsan"}
// ctx.body = 'GET Hello World! request param name:' + query.name;
// name=zhgnsane
// let query = ctx.querystring;
// ctx.body = 'GET Hello World! request param name:' + query;
const request = ctx.request;
const response = ctx.response;
// let query = request.query;
// {name : "zhgnsan"}
// ctx.body = 'GET Hello World! request param name:' + query.name;
// {
// method: 'GET',
// url: '/?name=zhgnsan',
// header: {
// host: 'localhost:8080',
// 'user-agent': 'curl/7.64.1',
// accept: '*/*'
// }
// }
console.log(request);
let query = request.querystring;
// name=zhgnsane
ctx.body = 'GET Hello World! request param name:' + query;
});
// 配置动态路由
// curl -X GET http://localhost:8080/get/zhgnsan
router.get('/get/:name', async (ctx, next) => {
let name = ctx.params.name;
ctx.body = "GET /get/" + name;
});
// 配置中间件
app.use(router.routes()).use(router.allowedMethods());
// 监听端口
app.listen(8080);
lixin-macbook:koa-example lixin$ node app.js
// GET请求
lixin-macbook:~ lixin$ curl -X GET http://localhost:8080?name=zhgnsan
GET Hello World! request param name:name=zhgnsan
// GET动态路由
lixin-macbook:~ lixin$ curl -X GET http://localhost:8080/get/zhgnsan
GET /get/zhgnsan