//操做文件用的 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"); });