stt / src /app.ts
yuanjiajun
feat: 文件服务
fc2888c
import Koa from 'koa';
import bodyParser from 'koa-body';
import mount from 'koa-mount';
import staticMiddleware from 'koa-static';
import fileRoutes from './routes/fileRoutes';
import { errorMiddleware } from './middleware/errorMiddleware';
import bodyparser from 'koa-bodyparser';
import path from 'path';
const app = new Koa();
// 自定义中间件解析二进制数据
app.use(async (ctx, next) => {
if (ctx.request.header['content-type'] === 'application/octet-stream') {
const chunks = [];
for await (const chunk of ctx.req) {
chunks.push(chunk);
}
ctx.request.body = Buffer.concat(chunks);
}
await next();
});
// 配置 bodyparser
app.use(bodyparser());
// 日志中间件
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`);
});
app.use(errorMiddleware);
app.use(bodyParser({ multipart: true }));
app.use(mount('/uploads', staticMiddleware(path.join(__dirname, '../../uploads'))));
app.use(fileRoutes.routes());
app.use(fileRoutes.allowedMethods());
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});