## 入口
```
const Koa = require("koa");
const app = new Koa();
const bodyParser = require("koa-bodyparser");
app.use(bodyParser());
const UserRouter = require("./routers/User")();
app.use(UserRouter.routes(), UserRouter.allowedMethods());
setTimeout(() => {}, 2000);
app.listen(3001, () => {
console.log("Server is running at http://localhost:3001");
});
```
## routers/User
```
const Router = require("@koa/router");// koa 路由
const router = new Router();
// get
/*
fetch("http://127.0.0.1:3000/users/1?asd=11").then((response) => {
response.json().then((data) => console.log(1, data));
});
*/
router.get("/users/:id?", async (ctx, next) => {
// 讀取請求頭
let header = ctx.request.headers;
console.log(header, header.host);
// {
// host: '127.0.0.1:3001',
// connection: 'keep-alive',
// 'cache-control': 'max-age=0',
// 'sec-ch-ua': '"Microsoft Edge";v="125", "Chromium";v="125", "Not.A/Brand";v="24"',
// 'sec-ch-ua-mobile': '?0',
// 'sec-ch-ua-platform': '"Windows"',
// 'upgrade-insecure-requests': '1',
// 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0',
// accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
// 'sec-fetch-site': 'none',
// 'sec-fetch-mode': 'navigate',
// 'sec-fetch-user': '?1',
// 'sec-fetch-dest': 'document',
// 'accept-encoding': 'gzip, deflate, br, zstd',
// 'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6'
// }
// 127.0.0.1:3001
let query = ctx.query;
console.log(query, query.asd);
let params = ctx.params;
console.log(params, params.id);
// 自定義設置響應頭
ctx.set("a", 1);
// 返回數據體
ctx.body = {
a: 1,
b: 2,
method: "GET",
query,
params,
};
next();
});
// post
/*
fetch("http://127.0.0.1:3000/users/1?asd=11", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "John Doe",
email: "johndoe@example.com",
}),
}).then((response) => {
response.json().then((data) => console.log(1, data));
});
*/
router.post("/users/:id", async (ctx, next) => {
const body = ctx.request.body;
console.log(body, body.name);
const query = ctx.query;
console.log(query, query.asd);
const params = ctx.params;
console.log(params, params.id);
ctx.body = {
a: 1,
b: 2,
method: "POST",
body,
query,
params,
};
next();
});
// delete
/*
fetch("http://127.0.0.1:3000/users/1?AAA=1", {
method: "DELETE",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
name: "John Doe",
email: "johndoe@example.com",
}),
}).then((response) => {
// console.log("response: ", response);
response.json().then((data) => console.log(1, data));
});
*/
router.delete("/users/:id", async (ctx, next) => {
let body = ctx.request.body;
console.log(body, body.name);
let query = ctx.query;
console.log(query, query.AAA);
let params = ctx.params;
console.log(params, params.id);
ctx.body = {
a: 1,
b: 2,
method: "DELETE",
body,
query,
params,
};
next();
});
// put
router.put("/users", async (ctx, next) => {
ctx.body = {
a: 1,
b: 2,
method: "PUT",
};
next();
});
// patch
router.patch("/users", async (ctx, next) => {
ctx.body = {
a: 1,
b: 2,
method: "PATCH",
};
next();
});
module.exports = () => {
return router;
};
```
## 常用中間件
| 名稱 | 安裝命令 | 作用 | 應用場景 |
| --- | --- | --- | --- |
| koa-router | npm install koa-router | 提供路由功能,幫助你定義和處理路由 | 在需要處理多個路由的Web應用中 |
| koa-bodyparser | npm install koa-bodyparser | 解析HTTP請求體,可以解析JSON、表單數據等 | 在需要處理用戶提交的數據的Web應用中 |
| koa-static | npm install koa-static | 托管靜態文件,如HTML、CSS、JavaScript文件和圖片等 | 在需要提供靜態資源訪問的Web應用中 |
| koa-session 或 koa-cookie | npm install koa-session或npm install koa-cookie | 處理會話和Cookie,可以幫助你實現用戶認證和授權 | 在需要用戶登錄和權限控制的Web應用中 |
| koa-logger | npm install koa-logger | 記錄請求日志,可以幫助你調試你的應用 | 在需要記錄和查看請求日志的Web應用中 |
| koa-json | npm install koa-json | 美化JSON響應 | 在需要返回格式化的JSON數據的Web應用中 |
| koa-compress | npm install koa-compress | 壓縮HTTP響應,可以幫助你提高應用的性能 | 在需要提高響應速度和減少網絡傳輸量的Web應用中 |
| koa-helmet | npm install koa-helmet | 增強HTTP響應安全性,設置了許多HTTP頭以防止常見的攻擊 | 在需要提高Web應用安全性的場景中 |
## cmd命令創建koa+node后端項目
#### Koa-generate
使用Koa開發后端服務固然方便容易,但是面對中大型項目,手動構建文件目錄和一些常見代碼是很低效的,因此便有開發者基于Koa開發出來Koa項目生成器–`Koa-generate`,這個工具可以讓開發者快速構建中大型項目的的項目目錄結構,加速開發進度;
首先我們需要配置環境,下載該庫:
`npm install -g koa-generator`
命令生成Koa項目:`koa2 project-name map-visual //或者 koa2 -e project-name`
* `koa2 project-name map-visual`:這個命令會創建一個新的Koa項目,使用的模板引擎是默認的jade(也被稱為pug)。
* `koa2 -e project-name`:這個命令也會創建一個新的Koa項目,但是使用的模板引擎是ejs。-e選項是–ejs的簡寫,表示使用ejs作為模板引擎。