articles.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. const express = require('express');
  2. const router = express.Router();
  3. const {Article, Category} = require('../../models')
  4. const {Op} = require('sequelize')
  5. /*
  6. 查询文章列表
  7. GET /admin/articles
  8. */
  9. router.get('/', async function(req, res, next) {
  10. try {
  11. const query = req.query
  12. //当前是第几页,如果不传,那就是第一页
  13. const currentPage = Math.abs(Number(query.currentPage)) || 1
  14. //每页显示多少条数据,如果不传,那就显示10条
  15. const pageSize = Math.abs(Number(query.pageSize)) || 10
  16. //计算 offset
  17. const offset = (currentPage - 1) * pageSize
  18. const condition = {
  19. order:[['id','DESC']],
  20. limit:pageSize,
  21. offset,
  22. include: [{
  23. model: Category,
  24. as: 'categoryInfo',
  25. attributes: ['id', 'name', 'level', 'parentId'],
  26. required: false // LEFT JOIN,即使没有分类也能返回文章
  27. }]
  28. }
  29. // 构建查询条件
  30. const whereConditions = {};
  31. // 标题搜索
  32. if(query.title){
  33. whereConditions.title = {
  34. [Op.like]:`%${query.title}%`
  35. }
  36. }
  37. // 分类筛选 - 支持多选和包含子分类
  38. if(query.categoryIds){
  39. let categoryIds = [];
  40. // 处理categoryIds参数(支持逗号分隔的多个ID)
  41. if(typeof query.categoryIds === 'string'){
  42. categoryIds = query.categoryIds.split(',').map(id => parseInt(id.trim())).filter(id => !isNaN(id));
  43. } else if(Array.isArray(query.categoryIds)){
  44. categoryIds = query.categoryIds.map(id => parseInt(id)).filter(id => !isNaN(id));
  45. } else {
  46. categoryIds = [parseInt(query.categoryIds)].filter(id => !isNaN(id));
  47. }
  48. if(categoryIds.length > 0){
  49. // 获取所有选中的分类及其子分类的ID
  50. const allCategoryIds = await getAllCategoryIdsWithChildren(categoryIds);
  51. whereConditions.category = {
  52. [Op.in]: allCategoryIds
  53. };
  54. }
  55. }
  56. // 如果有查询条件,添加到condition中
  57. if(Object.keys(whereConditions).length > 0){
  58. condition.where = whereConditions;
  59. }
  60. const {count ,rows} = await Article.findAndCountAll(condition)
  61. res.json({
  62. status:true,
  63. message:'成功',
  64. data:{
  65. articles:rows,
  66. pagination:{
  67. total:count,
  68. currentPage,
  69. pageSize
  70. }
  71. }
  72. });
  73. }catch(error){
  74. res.status(500).json({
  75. status:false,
  76. message:'失败',
  77. errors:[error.message]
  78. });
  79. }
  80. });
  81. /*
  82. 查询文章详情
  83. GET /admin/articles/:id
  84. */
  85. router.get('/:id', async function(req, res, next) {
  86. try {
  87. //获取文章id
  88. const {id} = req.params
  89. //查询文章
  90. const article = await Article.findByPk(id, {
  91. include: [{
  92. model: Category,
  93. as: 'categoryInfo',
  94. attributes: ['id', 'name', 'level', 'parentId'],
  95. required: false
  96. }]
  97. })
  98. if(article){
  99. res.json({
  100. status:true,
  101. message:'成功',
  102. data:article
  103. });
  104. }else{
  105. res.status(404).json({
  106. status:false,
  107. message:'文章未找到',
  108. });
  109. }
  110. }catch(error){
  111. res.status(500).json({
  112. status:false,
  113. message:'失败',
  114. errors:[error.message]
  115. });
  116. }
  117. });
  118. /*
  119. 创建文章
  120. POST /admin/articles/
  121. */
  122. router.post('/', async function(req, res, next) {
  123. try {
  124. // 添加请求日志
  125. console.log('=== 创建文章请求开始 ===');
  126. console.log('请求体大小:', JSON.stringify(req.body).length);
  127. console.log('Content字段长度:', req.body.content ? req.body.content.length : 0);
  128. console.log('Title字段长度:', req.body.title ? req.body.title.length : 0);
  129. //白名单过滤
  130. const body = filterBody(req)
  131. console.log('过滤后的数据:', {
  132. titleLength: body.title ? body.title.length : 0,
  133. contentLength: body.content ? body.content.length : 0,
  134. hasImage: !!body.img,
  135. type: body.type
  136. });
  137. const article = await Article.create(body)
  138. console.log('文章创建成功, ID:', article.id);
  139. console.log('=== 创建文章请求结束 ===');
  140. res.status(201).json({
  141. status:true,
  142. message:'成功',
  143. data:article
  144. });
  145. }catch(error){
  146. // 添加详细的错误日志
  147. console.error('=== 创建文章错误 ===');
  148. console.error('错误名称:', error.name);
  149. console.error('错误消息:', error.message);
  150. console.error('错误堆栈:', error.stack);
  151. console.error('请求体大小:', JSON.stringify(req.body).length);
  152. console.error('请求体:', JSON.stringify(req.body, null, 2));
  153. if(error.message === '标题不能为空' || error.message === '内容不能为空' ||
  154. error.message.includes('长度不能超过') || error.message.includes('不允许的脚本标签')){
  155. res.status(400).json({
  156. status:false,
  157. message:'请求参数错误',
  158. errors:[error.message]
  159. });
  160. }else if(error.name === 'SequelizeValidationError'){
  161. const errors = error.errors.map(e => e.message)
  162. res.status(400).json({
  163. status:false,
  164. message:'数据验证失败',
  165. errors
  166. });
  167. }else if(error.name === 'SequelizeDatabaseError'){
  168. console.error('数据库错误详情:', error.original);
  169. res.status(500).json({
  170. status:false,
  171. message:'数据库错误',
  172. errors:['数据库操作失败,请稍后重试']
  173. });
  174. }else if(error.name === 'SequelizeConnectionError'){
  175. res.status(500).json({
  176. status:false,
  177. message:'数据库连接错误',
  178. errors:['数据库连接失败,请稍后重试']
  179. });
  180. }else{
  181. res.status(500).json({
  182. status:false,
  183. message:'服务器内部错误',
  184. errors:['服务器处理请求时发生错误,请稍后重试']
  185. });
  186. }
  187. }
  188. });
  189. /*
  190. 删除文章
  191. GET /admin/articles/:id
  192. */
  193. router.delete('/:id', async function(req, res, next) {
  194. try {
  195. //获取文章id
  196. const {id} = req.params
  197. //查询文章
  198. const article = await Article.findByPk(id)
  199. if(article){
  200. await article.destroy()
  201. res.json({
  202. status:true,
  203. message:'成功',
  204. });
  205. }else{
  206. res.status(404).json({
  207. status:false,
  208. message:'文章未找到',
  209. });
  210. }
  211. }catch(error){
  212. res.status(500).json({
  213. status:false,
  214. message:'失败',
  215. errors:[error.message]
  216. });
  217. }
  218. });
  219. /*
  220. 更新文章
  221. GET /admin/articles/:id
  222. */
  223. router.put('/:id', async function(req, res, next) {
  224. try {
  225. //获取文章id
  226. const {id} = req.params
  227. //查询文章
  228. const article = await Article.findByPk(id)
  229. //白名单过滤
  230. const body = filterBody(req)
  231. if(article){
  232. await article.update(body)
  233. res.json({
  234. status:true,
  235. message:'成功',
  236. data:article
  237. });
  238. }else{
  239. res.status(404).json({
  240. status:false,
  241. message:'文章未找到',
  242. });
  243. }
  244. }catch(error){
  245. res.status(500).json({
  246. status:false,
  247. message:'失败',
  248. errors:[error.message]
  249. });
  250. }
  251. });
  252. /**
  253. * 获取分类及其所有子分类的ID列表
  254. * @param {Array} categoryIds - 分类ID数组
  255. * @returns {Promise<Array>} 包含所有分类ID的数组
  256. */
  257. async function getAllCategoryIdsWithChildren(categoryIds) {
  258. try {
  259. let allIds = [...categoryIds];
  260. // 递归获取所有子分类
  261. async function getChildrenIds(parentIds) {
  262. if (parentIds.length === 0) return [];
  263. const children = await Category.findAll({
  264. where: {
  265. parentId: {
  266. [Op.in]: parentIds
  267. }
  268. },
  269. attributes: ['id']
  270. });
  271. const childrenIds = children.map(child => child.id);
  272. if (childrenIds.length > 0) {
  273. allIds = allIds.concat(childrenIds);
  274. // 递归获取子分类的子分类
  275. const grandChildrenIds = await getChildrenIds(childrenIds);
  276. allIds = allIds.concat(grandChildrenIds);
  277. }
  278. return childrenIds;
  279. }
  280. await getChildrenIds(categoryIds);
  281. // 去重并返回
  282. return [...new Set(allIds)];
  283. } catch (error) {
  284. console.error('获取分类ID列表错误:', error);
  285. // 如果出错,返回原始ID列表
  286. return categoryIds;
  287. }
  288. }
  289. function filterBody(req){
  290. try {
  291. // 数据清理和验证
  292. const body = {
  293. title: req.body.title ? String(req.body.title).trim() : null,
  294. content: req.body.content ? String(req.body.content) : null,
  295. type: req.body.type ? parseInt(req.body.type) : null,
  296. img: req.body.img ? String(req.body.img).trim() : null,
  297. date: req.body.date ? new Date(req.body.date) : null,
  298. author: req.body.author ? String(req.body.author).trim() : null,
  299. category: req.body.category ? parseInt(req.body.category) : null,
  300. crop: req.body.crop ? parseInt(req.body.crop) : null,
  301. seoKeyword: req.body.seoKeyword ? String(req.body.seoKeyword).trim() : null,
  302. seoDescription: req.body.seoDescription ? String(req.body.seoDescription).trim() : null
  303. };
  304. // 验证必填字段
  305. if (!body.title) {
  306. throw new Error('标题不能为空');
  307. }
  308. if (!body.content) {
  309. throw new Error('内容不能为空');
  310. }
  311. // 验证标题长度 - 放宽限制以适应富文本编辑器
  312. if (body.title.length > 500) {
  313. throw new Error('标题长度不能超过500个字符');
  314. }
  315. // 验证内容长度 - 防止过大的内容
  316. if (body.content.length > 5000000) { // 5MB限制
  317. throw new Error('内容过长,请减少内容长度');
  318. }
  319. // 检查富文本内容是否包含危险标签或脚本
  320. const dangerousTags = /<script[^>]*>.*?<\/script>/gi;
  321. if (dangerousTags.test(body.content)) {
  322. throw new Error('内容包含不允许的脚本标签');
  323. }
  324. return body;
  325. } catch (error) {
  326. console.error('filterBody错误:', error);
  327. throw error;
  328. }
  329. }
  330. module.exports = router;