当前位置: 首页 > 后端技术 > Node.js

使用Express开发小说API接口服务1.0(三)

时间:2023-04-03 16:03:14 Node.js

使用Express开发小说API接口服务1.0(三)在线访问地址https://api.langpz.com/发现追书的API详情页之前没有下载神器第一章和上一章的返回值只能自己封装。App.js添加错误处理//捕获404并转发到错误处理程序app.use(function(req,res,next){consterr=newError('NotFound');err.status=404;next(err);});//errorhandlerapp.use(function(err,req,res,next){//设置局部变量,只在开发中提供错误res.locals.message=err.message;res.locals.error=req.app.get('env')==='development'?err:{};//渲染错误页面res.status(err.status||500);res.render('error');});这些只要把代码放在module.exports=app;多于。在list页面添加returnID,找到routes/chapter.js第29行替换res.send(JSON.stringify({"flag":1,"id":body._id,"chapters":body.chapters,“消息”:“确定”}));详情页添加上一章和下一章的返回值);//引用公共文件letrouter=express.Router();/**获取小说内容,返回小说内容paramlink{String}为小说列表接口chapters[0].linkhttp://chapter2.zhuishushushenqi.com/chapter/${link}*/router.get('/',function(req,res,next){if(!req.query.link){res.send(JSON.stringify({"flag":0,"msg":"Pleasepassinlink..."}));}//req.query.link编码转义letlink=encodeURIComponent(req.query.link);request.get(`${common.CHAPTER}/chapter/${link}`,function(err,response,body){if(err){res.send(JSON.stringify({"flag":0,"msg":"发生错误therequest..."}));}//解析返回的数据body=JSON.parse(body);if(body.ok){//再次请求列表页获取上一页和下一页if(req.query.id){//req.query.id编码转义letid=encodeURIComponent(req.query.id);让n=parseInt(req.query.n);如果(isNaN(n)){n=0;}request.get(`${common.API}/atoc/${id}?view=chapters`,function(err,response,body2){if(err){res.send(JSON.stringify({"flag":0,"msg":"请求发生错误..."}));}if(body2=="wrongparam"){res.send(JSON.stringify({"flag":0,"msg":"IncomingWrongID..."}));}else{//解析返回的数据body2=JSON.parse(body2);//检查页码是否超过小说章节号if(n>body2.chapters.length-1){res.send(JSON.stringify({"flag":0,"msg":"传入页码太大"}));}else{//如果有是上一页或下一页,否则返回链接返回假让上一个,下一个;body2.chapters[n-1]?prev=body2.chapters[n-1].link:prev=false;body2.chapters[n+1]?next=body2.chapters[n+1].link:next=false;如果(body2.chapters.length>0){res.send(JSON.stringify({"flag":1,"id":id,"chapter":body.chapter,"prev":prev,"next":接下来,“消息”:“确定”}));}}}});}else{res.send(JSON.stringify({"flag":1,"chapter":body.chapter,"msg":"OK"}));}}else{res.send(JSON.stringify({"flag":0,"msg":"传入链接有错误"}));}});});module.exports=router;访问http://localhost:3000/article?link=http://www.69shu.com/txt/1463...添加n和id参数n表示是哪一页。id是图书ID。github仓库访问地址https://github.com/lanpangzhi/novel-api