Koa的了解
Koaは、元のExpressチームによって作成された軽量で堅牢で表現力豊かなnodejsフレームワークです。
使用Koa
- koa安装
* $ npm i koa
- シンプルなコアサーバー
const Koa = require("koa");
//koa正常使用
let app = new Koa();
//使用 会有一个回调函数
ctx: context对象
app.use(async (ctx) => {
//ctx.request === req; ctx.response === res;
// ctx.response.body = "hello world";
ctx.body = "hello "
console.log(ctx.url);
})
- Koaはミドルウェアを使用して「アップストリーム」を制御し、「ダウンストリーム」を呼び出します。
- Koaは、ミドルウェア関数のセットを含むオブジェクトです。app.useの関数は、ミドルウェアとして理解できます。
- next();を介して別のミドルウェアに制御を移します。
let m1 = async function(ctx, next) {
console.log("m1");
//ctx.state 传递数据
//它就像一个中间间的贡献空间
ctx.state = {
perPage: 5,
totalPage: "13"
}
//将控制权,交给下一个中间件
next(); // ----->m2
// console.log("m1 end");
}
let m2 = async function(ctx, next) {
// console.log("m2");
console.log(ctx.state);
ctx.state = {
p: 1,
id: 14,
totalPage: 3
}
next(); //------->下一个中间件
// console.log("m2 end");
}
let m3 = async function(ctx, next) {
// console.log("m3");
// next();
// console.log("m3 end");
console.log(ctx.state);
ctx.body = "hello";
//状态码
// ctx.status = 404
}
// 中间件在实际使用,全部都是模板
app.use(m1);
app.use(m2);
app.use(m3);
コア一般的に使用されるミドルウェア
またルーター
インストール
npm i koa-router -S
使用する
const KOa = require("koa");
const Router = require("koa-router");
let app = new KOa();
let router = new Router();
router.get("/", async ctx => {
//会将 / 和 /index的请求,返回同一页面
ctx.redirect("/index");
ctx.body = "hello world";
})
router.get("/datail", async ctx => {
ctx.body = "详细页";
})
router.get("/getData", async ctx => {
// let indexData = fs.readFile("index.html");
let indexData = "w我是读取模板";
//简写
// ctx.body = {
// indexData
// }
ctx.render("/index2", {
indexData
})
})
app.use(router.routes());
app.listen(8889);
RESTful:インターフェース設計の原則
post / get
間違ったアプローチ
localhost:8000 / adduser
localhost:8000 / deleteuser
localhost:8000 / uodateuser
localhost:8000 / getuser正しいアプローチ
localhost:8000 /ユーザーリクエストメソッド
getget localhost:8000 / user delete delete
localhost:8000 / user put update
localhost:8000 / user post add
REST設計は通常、次の条件を満たす
必要があります。プログラムまたはアプリケーションはリソースとして抽象化する必要があります。
各リソースは一意のURIに対応します(URIはUniform Resource Identifierです)。
統一されたインターフェイスを使用
してリソースを操作します。リソースに対するさまざまな操作は行いません。リソースを変更します。
すべての操作がステートレスであることを識別します
koa-views
- 安装koa-views
npm i koa-views -S
- 使用する
const Views = require("koa-views");
app.use(Views(__dirname + "/views", {
extension: "pug"
}));
router.get("/", async ctx => {
// ctx.body = "hello world";
})
app.use(router.routes());
app.listen(8081);
koa-static
- koa-staticは、静的リソースをロードするためのミドルウェアであり、cssやjsなどの静的リソースがロードされます。
- 安装koa-static
npm i koa-static
使用koa-static
const static = require("koa-static);
app.use(static(__dirname+"/static))//加载静态文件的目录