koa 框架学习

163 阅读1分钟

1. 背景

koa框架是一个nodejs编写的http服务器,从事前端开发的话,并不一定要使用java来做后端,nodejs也是一个很好的选择

2. demo

2.1 快速的构建一个http服务器

npm init -y

npm install koa

//使用koa启动一个http服务
const Koa = require("koa");
const app = new Koa();
//koa没有路由系统,只有中间件功能, ctx: 上下文对象,包括请求和响应
app.use(ctx => {
    ctx.body = "first koa";
})
app.listen(3000, () => {
    console.log("http://localhost:3000");
})

node app.js 直接启动访问

image.png

2.2 动态路由引入

koa 根深是没有路由功能的,需要借助router主键来实现路由功能

前提准备

npm install @koa/router

const Router = require("@koa/router");

const router = new Router();

app.use(router.routes()) .use(router.allowedMethods);

用法:

router.get("/user/:id", ctx => {
    console.log(ctx.params);
    ctx.body = "user page";
})

2.3 静态资源托管模块

npm install koa-static

设置请求的虚拟路径

npm install koa-mount

const static = require("koa-static");
const path = require("path");
const mount = require("./koa-mount");
app.use("/foo", static(path.join(__dirname, "./public")));

设置路由跳转

router.get("/redirect", ctx => {
    //针对的是同步请求
    ctx.body = "redirect front page";
    ctx.redirect("/take");
});
//就是用/foo代替./public
app.use(
    mount("/foo", static(path.join(__dirname, "./public")))
);

2.3 合并中间件

npm install koa-compose

app.use(compose([one,two,three]));

3 学习途径

www.bilibili.com/video/BV1W6…

看到第15章节了