undefined
前言
Expressive HTTP middleware framework for node.js to make web applications and APIs more enjoyable to write.(Github)
下载依赖
引入依赖
1
| const Koa = require("koa");
|
创建Web服务器
1 2 3 4 5
| const app = new Koa(); app.use(function (context, next) { context.body = ""; }); app.listen(8080);
|
1 2 3 4 5 6 7
| const app = new Koa(); app.use(function (context, next) { context.body = ""; }); app.listen(8080, function () { console.log(`http://127.0.0.1:8080`); });
|
1 2 3 4 5 6 7
| const app = new Koa(); app.use(function (context, next) { context.body = ""; }); app.listen(8080, "0.0.0.0", function () { console.log(`http://127.0.0.1:8080`); });
|
中间件
1 2 3
| app.use(function (context, next) { ... });
|
继续下一个中间件
处理请求
获取Nodejs请求对象
1
| const request = context.req;
|
获取Koa请求对象
1
| const request = context.request;
|
获取请求行
获取请求URL
1
| const path = context.request.path;
|
1
| const path = context.path;
|
获取请求方法
1
| const method = context.request.method;
|
1
| const method = context.method;
|
处理响应
获取Nodejs响应对象
1
| const response = context.res;
|
获取Koa响应对象
1
| const response = context.response;
|
设置响应体并返回响应
路由
下载依赖
引入依赖
1
| const KoaRouter = require("@koa/router");
|
定义路由
- 如果没有注册
router.allowedMethods(),则访问没有匹配的路由时会返回Not Found
- 如果注册了
router.allowedMethods(),则访问没有匹配的路由时会返回Method Not Allowed
1 2 3 4 5 6 7 8
| const router = new KoaRouter({ prefix: "/api" });
router.get("/", function (context, next) { ... });
app.use(router.routes()); app.use(router.allowedMethods());
|
处理请求
获取请求参数
query
1 2 3
| router.get("/", function (context, next) { const query = context.query; });
|
path
1 2 3
| router.get("/:id", function (context, next) { const id = context.params.id; });
|
下载依赖
1
| npm install koa-bodyparser
|
1 2 3 4 5 6 7
| const bodyParser = require("koa-bodyparser");
app.use(bodyParser());
app.use(function (context, next) { const body = context.request.body; });
|
下载依赖
1
| npm install @koa/multer multer
|
1 2 3 4 5 6 7
| const multer = require("@koa/multer");
const formParser = multer();
app.use(formParser.any(), function (context, next) { const body = context.request.body; });
|
解析单个文件上传请求参数
1 2 3 4 5 6 7
| const multer = require("@koa/multer");
const upload = multer({ dest: "./uploads" });
app.use(upload.single("key"), function (context, next) { const file = context.request.file; });
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const multer = require("@koa/multer");
const upload = multer({ storage: multer.diskStorage({ destination: function (request, file, callback) { callback(null, "./uploads"); }, filename: function (request, file, callback) { callback(null, file.originalname); } }) });
app.use(upload.single("key"), function (context, next) { const file = context.request.file; });
|
解析多个文件上传请求参数
1 2 3 4 5 6 7
| const multer = require("@koa/multer");
const upload = multer({ dest: "./uploads" });
app.post("/", upload.array("key"), function (context, next) { const files = context.request.files; });
|
完成