Joey / src /app.ts
yuanjiajun
feat: 变量
f6d320c
raw
history blame contribute delete
933 Bytes
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}`);
});