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

使用Express开发新颖的API接口服务1.0(一)

时间:2023-04-03 20:31:54 Node.js

使用Express开发新颖的API接口服务1.0(一)1.0版本技术栈使用express-generator、express、request、morgan、file-stream-rotator。接口使用追书神器API。目前的界面设计包括首页、小说详情页、搜索、小说文章列表页、排行榜API。github创建仓库先创建仓库放文件然后clone创建的仓库gitclonehttps://github.com/lanpangzhi/novel-api.gitinstallexpress-generator快速生成项目npminstall-gexpress-generator并执行express--no-viewnovel-apicdnovel-apinpminstallnpminstallrequestfile-stream-rotator-S//LinuxMacOSDEBUG=novel-api:*&npmstart//windowssetDEBUG=novel-api:*&npmstart生成的目录结构和文件设置cors跨域打开项目根目录app.js,放在路由上。app.all('*',function(req,res,next){res.header("Access-Control-Allow-Origin","*");res.header("Access-Control-Allow-Headers","Origin,X-Requested-With,Content-Type,Accept");res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");res.header("X-Powered-By",'3.2.1')??res.header("Content-Type","application/json;charset=utf-8");next()});将日志写入本地文件并按时间划分日志日志写入本地磁盘需要在app.js文件中引入fs和file-stream-rotator模块。让fs=require('fs');让FileStreamRotator=require('file-stream-rotator');//日志按时间模块划分//下面代码写在varapp=express();下面让logDir=路径。join(__dirname,'log');//检查logDir是否存在,如果不存在,创建fs.existsSync(logDir)||fs.mkdirSync(logDir);//日志分流letaccessLogStream=FileStreamRotator.getStream({date_format:'YYYYMMDD',filename:path.join(logDir,'access-%DATE%.log'),frequency:'daily',冗长:假});//日志中间件app.use(logger('combined',{stream:accessLogStream}));创建common文件在项目根目录下创建一个common文件夹,然后在里面新建一个common.json文件{"API":"http://api.zhuishushushenqi.com","PIC":"http://statics.zhuishushushenqi.com","CHAPTER":"http://chapter2.zhuishushushenqi.com"}API域名:http://api.zhuishushenqi.com图片域名:http://statics.zhuishushenqi。com章节域名:http://chapter2.zhuishushenqi...首页界面1.0版本首页界面直接返回热榜前20名数据。修改app.js文件路由中间件配置app.use('/index',indexRouter);修改routes/index.js文件letexpress=require('express');letrequest=require('request');letcommon=require('../common/common.json');//引用public文件letrouter=express.Router();/**Top100首页Top100最热图书追踪榜获取单次排名http://api.zhuishushenqi.com/ranking/{rankingId}*/router.get('/',function(req,res,next){//请求跟随的最热图书前100榜单request.get(`${common.API}/ranking/54d42d92321052167dfb75e3`,function(error,response,body){if(error){res.send(JSON.stringify({"flag":0,"msg":"请求发生错误..."}));}//解析返回数据取前20条,并添加图片url链接body=JSON.parse(body);if(body.ok){letbooks=body.ranking.books.slice(0,19);books.forEach(element=>{element.cover=common.PIC+element.cover;});res.send(JSON.stringify({"flag":1,"books":books,"msg":"OK"}));}else{res.send(JSON.stringify({"flag":0,"msg":"rankingId有问题"}));}});});module.exports=路由r;访问http://localhost:3000/index查看返回数据。1.0版本的搜索界面只取前40条数据,可以模糊搜索。修改app.js文件的路由中间件配置,删除用户。让searchRouter=require('./routes/search');app.use('/search',searchRouter);然后删除routes文件夹下的users.js,新建search.jsletexpress=require('express');letrequest=require('request');letcommon=require('../common/common.json');//引用公共文件letrouter=express.Router();/**模糊搜索接口返回fuzzy搜索前40条数据http://api.zhuishushenqi.com/book/fuzzy-search?query={name}*/router.get('/',function(req,res,next){//判断查询参数是否传递if(req.query.query){//req.query.query编码转义letquery=encodeURIComponent(req.query.query);request.get(`${common.API}/book/fuzzy-search?query=${query}`,function(error,response,body){if(error){res.send(JSON.stringify({"flag":0,"msg":"Arequesterror..."}));}//解析返回的数据body=JSON.parse(body);if(body.ok){if(body.books.length==0){res.send(JSON.stringify({"flag":0,"msg":"找不到书,试试其他名字。"}));}//获取前40个项目并添加图片url链接letbooks=body.books.slice(0,39);books.forEach(element=>{element.cover=common.PIC+element.cover;});res.send(JSON.stringify({"flag":1,"books":books,"msg":"OK"}));}else{res.send(JSON.stringify({"flag":0,"msg":"请求出错..."}));}});}else{res.send(JSON.stringify({"flag":0,"msg":"PleasepassEnterthequeryparameter"}));}});module.exports=router;访问http://localhost:3000/search/?query=Zetian可以看到返回的数据,喜欢的话,可以给github点个star谢谢我的博客和github地址https://github.com/lanpangzhihttp://blog.langpz.com参考https://github.com/expressjs/morganhttps://juejin.im/entry/593a3fdf61ff4b006c737ca4https://github.com/jianhui1012/bookreader/wiki/API-%E6%8E%A5%E5%8F%A3%E6%96%87%E6%A1%A3