Node.js+Express+TypeScript+Prisma分页接口返回空数组问题
问题分析与修复方案
你的分页接口返回空数组,核心是两个低级错误导致的:参数传递顺序颠倒,分页偏移量计算逻辑完全错误。
错误点拆解
Router层参数传递顺序错误
Dao层的listApplicantsWithPagination函数定义是先接收page(页码),再接收pageSize(每页条数),但你的Router调用时传的是parsedPageSize和offset,不仅顺序反了,还把错误计算的offset当成页码传给了Dao,直接导致后续分页逻辑完全混乱。Dao层分页偏移量(skip)计算错误
当前Dao里的skip: (parsedPage + 10) * parsedPageSize完全不符合分页逻辑,+10是无意义的操作,标准分页的偏移量应该是(页码 - 1) * 每页条数——比如第1页不需要跳过数据,第2页跳过前pageSize条,以此类推。
修正后的代码
Router层代码
getEntriesRouter.get("/list-entries", authenticateToken, async (req: CustomRequest, res) => { try { const { page = 1, pageSize = 50 } = req.query; const parsedPage = parseInt(page as string, 10); const parsedPageSize = parseInt(pageSize as string, 10); if (isNaN(parsedPage) || isNaN(parsedPageSize) || parsedPage < 1 || parsedPageSize < 1) { return res.status(400).json({ status: false, message: '无效的page或pageSize参数。', }); } // 修正参数顺序:先传页码,再传每页条数 const applicants = await ApplicantDao.listApplicantsWithPagination(parsedPage, parsedPageSize); return res.status(200).json({ status: true, message: "成功获取申请者列表", data: applicants, }); } catch (error: any) { return res.status(500).json({ status: false, error: error.message, }); } });
Dao层代码
export const listApplicantsWithPagination = async (page: number, pageSize: number): Promise<Applicant[]> => { try { console.log('当前页码:', page); console.log('每页条数:', pageSize); const applicants = await db.applicant.findMany({ select: { id: true, email: true, firstname: true, lastname: true, phone: true, country: true, role: true, github: true, linkedin: true, website: true, resume: true, }, // 标准分页偏移量计算:(页码-1)*每页条数 skip: (page - 1) * pageSize, take: pageSize, }); console.log('查询到的申请者:', applicants); return applicants; } catch (error) { console.error("获取申请者列表(带分页)出错:", error); throw error instanceof Error ? error.message : "未知错误"; } };
修正说明
- Router层:删掉了错误的
offset计算,严格按照Dao函数定义的参数顺序传递page和pageSize。 - Dao层:移除了重复的类型转换(Router已经完成校验和转换),把
skip改成标准分页公式,同时优化了错误处理逻辑,确保抛出的错误信息格式统一。
内容的提问来源于stack exchange,提问作者Plus Ultra
相关产品推荐
相关产品推荐

