import Koa from 'koa'; import { koaBody } from 'koa-body'; import serve from 'koa-static'; import routes from './router.js'; const app = new Koa(); // 全局异常处理 process.on('uncaughtException', (err, origin) => { console.log(`Caught exception: ${err}\n` + `Exception origin: ${origin}`); }); app.use(serve('../client/build')); // 统一接口错误处理 app.use(async (ctx, next) => { try { await next(); if (ctx.response.status === 404 && !ctx.response.body) { ctx.throw(404); } } catch (error) { const { url = '' } = ctx.request; const { status = 500, message } = error; if (url.startsWith('/api')) { ctx.status = typeof status === 'number' ? status : 500; ctx.body = { msg: message, }; } } }); app.use(koaBody()); // 加载数据路由 app.use(routes.routes()); // 静态资源目录, app.listen(3001, () => { console.log('Server is running on http://localhost:3001'); });