koa的基本使用

//操做文件用的
import * as fs from "fs";

//koa 本體
import * as Koa from "koa";

//這個是用來拼路徑的
import * as path from "path";

//這個能夠拿來作路由
import * as Router from "koa-router";

//這個能夠拿來作上傳功能,以及獲取post參數
import * as koaBody from "koa-body";

//要使用 koa-send 來支持下載功能
import * as send from 'koa-send';

const app = new Koa();

//使用 koaBody 中間件  若是沒有這句的話 ctx.request.body 將拿不到參數
app.use(koaBody());

//如今這個 router 實例 就是路由對象
const router = new Router();

//設置 get 路由  瀏覽器訪問 http://127.0.0.1:3000/get?1=11 
router.get("/get", async (ctx) => {
    //拿到 { '1': '11' }
    console.log(ctx.query);

    //拿到 { '1': '11' }
    console.log(ctx.request.query);
});

//設置 get 路由  瀏覽器訪問 http://127.0.0.1:3000/download/1.png
router.get("/download/:name", async (ctx) => {

    //ctx.params.name 等於 1.png
    const fileName = ctx.params.name;

    const path = `./Asset/${fileName}`;

    //這個是重點,瀏覽器訪問 http://127.0.0.1:3000/download/1.png 的時候,就靠他來下載 1.png 文件
    await send(ctx, path);
});

//設置 post 路由  瀏覽器訪問 http://127.0.0.1:3000/post  參數:{2:222}
router.post("/post", (ctx) => {
    //使用了中間件以後,就能夠拿到 post 請求提交的參數  {2:222} 
    console.log(ctx.request.body);
});

//使用路由中間件
app.use(router.routes());
app.use(router.allowedMethods());

//設置監聽端口
app.listen(3000, () => {
    console.log("服務器開啓 127.0.0.1:3000");
});
相關文章
相關標籤/搜索