koaサーバーフレームワークを0から1まで構築する

koaフレームワークとexpressの違い

express:
ルーティングやテンプレートなどの機能を備えた完全なアプリケーションフレームワークが含まれており、多くのスペースを占有します
。koa:
Koaモジュールは、モジュール性が高く、メモリフットプリントが小さく、実行速度が速いミドルウェアカーネルです。

0から1までのExpressフレームワークを構築する

  1. pakage.jsonを初期化します

npm init

  1. インストールの依存関係
    次のコードをpakage.jsonに貼り付け、npminstallを実行します
"koa": "^2.13.1",
"koa-bodyparser": "^4.3.0",
"koa-onerror": "^4.1.0",
"koa-router": "^10.0.0",
"koa-static": "^5.0.0"
  1. 新しい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);

  1. ルートディレクトリに新しいルートフォルダを作成します
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
  1. ルートディレクトリのveiwの下に新しいveiwおよびテンプレートファイルindex.htmlフォルダを作成します
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>123</title>
	</head>
	<body>
		<p>hello</p>
	</body>
</html>

  1. 最終目次
    ここに画像の説明を挿入
    シンプルなフレームワークが完成しました!ログイン後/リクエストヘッダー処理/統一フォーマットへの復帰/データベースリンク/ログインメカニズム処理は引き続き追加

koa-generatorを使用してすばやく構築する

npm install koa-generator -g

コアプロジェクト名

成功!依存関係をインストールして実行するだけです。フレームワークで構築
され
たapp.js構成に注意してください(アップグレードされたバージョンと呼ばれます)

//中间件配置时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!';
});

オンラインクエリの構成は基本的に

//中间件配置时app.js
app.use(async (ctx, next) => {
    
    
  await next()
});
//使用时 router中
router.post('/index', async (ctx, next) => {
    
    
	ctx.body=ctx
}

長時間チェックした後、インターフェース部分は処理されません。後で、フレームワーク内のこれがctx
フレームワーク構成であることがわかります。変更は次のように変更されます。

//中间件配置时app.js
app.use(function *(next){
    
    
  yield next;
 });
//使用时 router中
router.get('/', function *(next) {
    
    
  this.body = 'this is a users response!';
});

ctxについて

https://koa.bootcss.com/
https://blog.csdn.net/weixin_43392420/article/details/85676384リンクの説明を追加します。

おすすめ

転載: blog.csdn.net/qq_40969782/article/details/113565239