app.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. console.log("aap.js 中间件处理")
  25. console.log(ctx)
  26. await next();
  27. } catch (err) {
  28. if (err.name === 'UnauthorizedError') {
  29. ctx.body = {
  30. code: 10018,
  31. data: '',
  32. message: 'TOKEN 无效,请重新登录', // 自定义错误信息
  33. };
  34. return;
  35. } else if (err.message.indexOf('options.maxFileSize') > -1) {
  36. ctx.body = {
  37. code: 102,
  38. data: '',
  39. message: '超出最大限制,文件最大为5M', // 自定义错误信息
  40. };
  41. return;
  42. } else {
  43. ctx.body = {
  44. code: -1,
  45. data: '',
  46. message: err.message,
  47. };
  48. }
  49. }
  50. });
  51. // 文件上传中间件
  52. app.use(
  53. koaBody({
  54. multipart: true,
  55. formidable: {
  56. uploadDir: path.join(__dirname, 'public/'), // 设置文件上传目录
  57. keepExtensions: true, // 保持文件的后缀
  58. allowEmptyFiles: false, // 允许上传空文件
  59. maxFiles: 1, // 设置同时上传文件的个数
  60. maxFileSize: 5 * 1024 * 1024, // 文件大小限制,默认2M
  61. maxFields: 10, // 设置字段数量
  62. maxFieldsSize: 3 * 1024 * 1024, // 设置上传文件内存大小
  63. },
  64. }),
  65. );
  66. //addbywanghao sso 20250512 /^\/api\/user\/ssoLogin/,
  67. // token 鉴权
  68. app.use(
  69. koajwt({ secret: config.JWT_SECRET }).unless({
  70. path: [
  71. /^\/api\/editor\/user\/ssoLogin/,
  72. /^\/api\/editor\/user\/login/,
  73. /^\/api\/editor\/user\/admin\/login/,
  74. /^\/api\/editor\/user\/wechat/,
  75. /^\/api\/editor\/user\/sendEmail/,
  76. /^\/api\/editor\/user\/regist/,
  77. /^\/api\/editor\/user\/password/,
  78. /^\/api\/editor\/admin\/page\/detail/,
  79. /^\/api\/editor\/ai\/proxy/,
  80. /^\/api\/editor\/firefly/,
  81. ],
  82. }),
  83. );
  84. routerInstaller(app);
  85. app.on('error', errorHandler);
  86. module.exports = app;