The difference between koa framework and express
express:
Contains a complete application framework with functions such as routing and templates, and takes up a lot of space
.
Koa : Koa module is a middleware core with higher modularity, small memory footprint, and fast running
Build express framework from 0 to 1
- Initialize pakage.json
npm init
- Installation dependencies
Paste the following code into pakage.json and execute npm install
"koa": "^2.13.1",
"koa-bodyparser": "^4.3.0",
"koa-onerror": "^4.1.0",
"koa-router": "^10.0.0",
"koa-static": "^5.0.0"
- New app.js
const Koa = require('koa')//引入koa中间件
const app = new Koa()
const onerror = require('koa-onerror'); //异常记录
const fs = require('fs');
//设置路由中间件
app.use(async (ctx, next) => {
await next()
});
//处理post方法接收到的数据
app.use(require('koa-bodyparser')());
//异常处理
onerror(app);
// 建立路由文件
const index = require('./router/index')
app.use(index.routes(), index.allowedMethods());
//设置静态目录
app.use(require('koa-static')(__dirname + '/public'));
// 异常处理
app.on('error', (err, ctx) => {
ctx.res.writeHead(200,{
'content-Type':'application/json'
});
ctx.res.end(JSON.stringify(err));
});
app.listen(3001);
- Create a new route folder in the root directory
const koaRouter = require('koa-router');
const router = koaRouter();
//处理get请求
router.get('/oindex', async (ctx, next) => {
let code="222"
let msg="成功"
let data={
name:'111',status:"成功"}
ctx.body={
code,
msg,
data
}
});
//处理post请求
router.post('/index', async (ctx, next) => {
let code="222"
let msg="成功"
let data={
name:'111',status:"成功"}
ctx.body=ctx
//返回异常
// const error = new Error()
// error.code = 10000
// error.msg = '无此用户'
// throw(error);
});
module.exports = router
- Create a new veiw and template file index.html folder under veiw in the root directory
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>123</title>
</head>
<body>
<p>hello</p>
</body>
</html>
- Final table of contents The
simple framework is completed! Post-login/request header processing/return to unified format/database link/login mechanism processing continue to add
Use koa-generator to quickly build
npm install koa-generator -g
koa project name
success! Just install the dependency and run it.
Pay attention to
the app.js configuration built with the framework (it is said to be an upgraded version)
//中间件配置时app.js
app.use(function *(next){
var start = new Date;
yield next;
var ms = new Date - start;
console.log('%s %s - %s', this.method, this.url, ms);
});
//使用时 router中
router.get('/', function *(next) {
this.body = 'this is a users response!';
});
The online query configuration is basically
//中间件配置时app.js
app.use(async (ctx, next) => {
await next()
});
//使用时 router中
router.post('/index', async (ctx, next) => {
ctx.body=ctx
})
After checking for a long time, the interface part will not be processed. Later, it is found that this in the framework is the ctx
framework configuration. The modification is changed to:
//中间件配置时app.js
app.use(function *(next){
yield next;
});
//使用时 router中
router.get('/', function *(next) {
this.body = 'this is a users response!';
});
About ctx
https://koa.bootcss.com/
https://blog.csdn.net/weixin_43392420/article/details/85676384 Add link description