File size: 933 Bytes
f6d320c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
import Koa from 'koa';
import bodyParser from 'koa-bodyparser';

import combinedRouter from '@/controllers';

const app = new Koa();
const port = process.env.PORT || 3000;

// 日志中间件
app.use(async (ctx, next) => {
  const start = Date.now();
  await next();
  const ms = Date.now() - start;
  console.log(`${ctx.method} ${ctx.url} - ${ctx.status} ${ms}ms`);
});

// 使用 bodyparser 解析 JSON 请求体
app.use(bodyParser());

// 自定义中间件处理二进制数据
app.use(async (ctx, next) => {
  if (ctx.is('application/octet-stream')) {
    const buffers = [];
    for await (const chunk of ctx.req) {
      buffers.push(chunk);
    }
    ctx.request.body = Buffer.concat(buffers);
  }
  await next();
});

// 结合路由中间件
app.use(combinedRouter.routes()).use(combinedRouter.allowedMethods());

// 启动服务器
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});