app.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. const Koa = require('koa');
  2. const { koaBody } = require('koa-body');
  3. const cors = require('koa2-cors');
  4. const koajwt = require('koa-jwt');
  5. const path = require('path');
  6. const { routerInstaller } = require('./utils/installer');
  7. const errorHandler = require('./error');
  8. const config = require('./config');
  9. const app = new Koa();
  10. app.use(
  11. cors({
  12. credentials: true, // 允许携带认证信息(如cookies)
  13. exposeHeaders: ['Content-Disposition'], // 下载文件时,响应头中包含filename
  14. }),
  15. );
  16. /**
  17. * 中间件处理
  18. * 1. Cookie令牌验证。
  19. * 2. 参数、请求地址打印,通过monitor排查错误日志。
  20. * 3. 拦截通过throw抛出的异常。
  21. */
  22. app.use(async (ctx, next) => {
  23. try {
  24. await next();
  25. } catch (err) {
  26. if (err.name === 'UnauthorizedError') {
  27. ctx.body = {
  28. code: 10018,
  29. data: '',
  30. message: 'TOKEN 无效,请重新登录', // 自定义错误信息
  31. };
  32. return;
  33. } else if (err.message.indexOf('options.maxFileSize') > -1) {
  34. ctx.body = {
  35. code: 102,
  36. data: '',
  37. message: '超出最大限制,文件最大为5M', // 自定义错误信息
  38. };
  39. return;
  40. } else {
  41. ctx.body = {
  42. code: -1,
  43. data: '',
  44. message: err.message,
  45. };
  46. }
  47. }
  48. });
  49. // 文件上传中间件
  50. app.use(
  51. koaBody({
  52. multipart: true,
  53. formidable: {
  54. uploadDir: path.join(__dirname, 'public/'), // 设置文件上传目录
  55. keepExtensions: true, // 保持文件的后缀
  56. allowEmptyFiles: false, // 允许上传空文件
  57. maxFiles: 1, // 设置同时上传文件的个数
  58. maxFileSize: 5 * 1024 * 1024, // 文件大小限制,默认2M
  59. maxFields: 10, // 设置字段数量
  60. maxFieldsSize: 3 * 1024 * 1024, // 设置上传文件内存大小
  61. },
  62. }),
  63. );
  64. // token 鉴权
  65. app.use(
  66. koajwt({ secret: config.JWT_SECRET }).unless({
  67. path: [
  68. /^\/api\/editor\/user\/login/,
  69. /^\/api\/editor\/user\/admin\/login/,
  70. /^\/api\/editor\/user\/wechat/,
  71. /^\/api\/editor\/user\/sendEmail/,
  72. /^\/api\/editor\/user\/regist/,
  73. /^\/api\/editor\/user\/password/,
  74. /^\/api\/editor\/admin\/page\/detail/,
  75. /^\/api\/editor\/ai\/proxy/,
  76. /^\/api\/editor\/firefly/,
  77. ],
  78. }),
  79. );
  80. routerInstaller(app);
  81. app.on('error', errorHandler);
  82. module.exports = app;