### 作业
- 第一题
```js
// 模拟数据库
function Sql(){
return new Promise((resolve)=>{
setTimeout(() => {
resolve ([
{id:'22',name:"王华",email:"1111"},
{id:'18',name:"李白",email:"2222"},
{id:'99',name:"小芳",email:"3333"},
])
}, 3000);
})
}
// 中间件:拦截所有请求,并在控制台中输出请求的 URL 和 HTTP 方法。
app.use(async (ctx,next)=>{
// 时间
let time = new Date()
const tt = `[Info][${time.toLocaleString()}][${ctx.request.method}][${ctx.request.url}]`
console.log(tt);
await next()
})
Router.get("/",async(ctx,next)=>{
ctx.body = `"message": "Hello, Welcome to Koa!"`
})
Router.get("/users",async(ctx)=>{
const ele = await Sql()
ctx.body = ele
})
```
- 第二题
- api.http
```h
@url = http://localhost:8000
### get
GET {{url}}/ HTTP/1.1
X-Auth-Token: valid-token-123
###
GET {{url}} HTTP/1.1
```
```js
app.use(async(ctx,next)=>{
// 模拟一个简单的 `X-Auth-Token`
const token = `valid-token-123`
// 获取请求头中的值
const va = ctx.headers['x-auth-token']
if (va === token ) {
// 允许请求继续
await next()
}
else{
ctx.status = 401
ctx.body =
// 返回JSON字符串
{
error: "Unauthorized",
message: "Invalid or missing token"
}
}
})
// 示例路由
Router.get('/', async (ctx) => {
ctx.body = { message: "成功" };
});
```
- 第三题
- api.http
```h
@url = http://localhost:8000
### post
POST {{url}}/api/data HTTP/1.1
Content-Type: application/json
{
"name": "John",
"age": 30
}
```
```js
// 请求日志中间件
app.use(async (ctx,next)=>{
// 时间
let time = new Date()
const tt = `[REQUEST][${time.toLocaleString()}][${ctx.request.method}][${ctx.request.url}]`
console.log(tt);
await next()
})
// 数据格式化中间件(仅对 POST 请求生效)
app.use(async (ctx,next)=>{
if (ctx.request.method === 'POST') {
const object = ctx.request.body || {}
const ff = {} // 存储新数组
for (const key in object) {
ff[key.toUpperCase()] = object[key]
}
ctx.request.body = ff
console.log(ctx.request.body);
}
})
Router.post("/api/data",async(ctx,next)=>{
ctx.body = ff
})
```