一直以来都在关注nodejs,直到最近空闲下来,才尝试写写nodejs小demo。文章若有错误欢迎批评指正!来自一位不知名的前端。
一、本demo刚开始采用koa2开发,后面因为koa2的异步响应很差处理(还在研究中)改用express;后续会尝试使用koa2改造。
二、http请求(csrf伪造)主要参考netmusic-node;其余部分思路参考NeteaseCloudMusicApi。
三、本项目预览地址https://music.jeeas.cn/html
以get方式请求 一、搜索歌曲名 params[s=歌曲名,type,offset,limit] getApi/search?s=歌曲名 二、单曲播放地址 params[id=歌曲id,br] getApi/music/url?id=25643093 三、歌词 params[id] getApi/lyric?id=25643093 四、单曲详情 params[id] getApi/music/detail?id=25643093 五、专辑详情 params[id] getApi/album/detail?id=2263164 六、歌单类型列表 params[] getApi/playlist/catlist 七、歌单类型列表-热门类型 params[] getApi/playlist/hot 八、推荐新音乐 params[] getApi/personalized/newsong 九、搜索hot params[] getApi/search/hot 十、推荐歌单 params[] getApi/personalized
"dependencies": { "apicache": "^1.5.2", "big-integer": "^1.6.47", "crypto": "^1.0.1", "ejs": "^2.7.1", "express": "^4.17.1", "express-rate-limit": "^3.5.3", "fs-extra": "^8.1.0", "redis": "^2.8.0", "request": "^2.88.0", "socket.io": "~2.1.1" }
apicache:请求cache缓存,防止api调用过于频繁ip被禁掉
ejs:数据模板
express-rate-limit:express内部封装api访问限制
redis:数据临时存储到redis中未涉及到数据库操做
socket.io:socket基础包
前端
server.js
项目启动后redis的链接状态以及soketIo会挂载在整个server下,方便后面调用。node
... var redisClient = false; var ioSocket = null; //启动查看redis状态 redis.initRedis(function(client) { redisClient = client && client != '' && client != null ? true : false; io.redisClient = redisClient; }); ... socketServer.initServer(io); //static //api访问限制20s内60次 //cache 缓存2分钟 2 minutes 0.05 minutes=3s //设置跨域访问 //使用ejs //使用路由 app.use(router); ... server.listen(port, () => { console.log('Socket Server listening at port %d', port); console.log('Visit http://127.0.0.1:%d', port); console.log('Hello, I\'m %s, how can I help?', serverName); });
http.js
项目http请求简单封装git
var http = require('http'); ... function WebAPI(options, callback) { //.... var httpClients = http.request({ hostname: 'music.163.com', method: method, path: options.path, headers: {...} },function(req, res) { req.on('error', function(err) { //请求异常处理... }); req.on('data', function(chunk) { //获取数据... }); req.on('end', function() { //网易云api调用有时候会响应为空,为空时从新发起请求 //数据接收完毕处理rsp //回调以前用websoket向全部clients广播消息,以及更新redis callback(rsp); }) }); //网易云csrf伪造,详情crypto.js httpClients.write('params=' + cryptoreq.params + '&encSecKey=' + cryptoreq.encSecKey); httpClients.end(); } ... module.exports = { WebAPI: WebAPI, }
socket.js
github
服务端接收clients的消息发送,以及向全部clients广播消息(api调用数)web
function initServer(io,callback) { if (io) { io.on('connection', function(socket) { socket.on('message', function(data) { console.log(data.message) }); //console.log('emit全部人推送,broadcast除某个套接字之外的全部人发送消息,eg:connection不推送'); //向全部链接推送news消息 socket.broadcast.emit('news', { message: 'a new connection', newsType: 'server-prop' }); if(callback){ callback(socket) } socket.on('disconnect', function() { //console.log('disconnect') }); }); } } module.exports = { initServer: initServer };
redis.js
redis简单的查询更新封装redis
var redis = require('redis'); var client = null; function initRedis(callback) { if (!client) { client = redis.createClient(6379, '127.0.0.1'); } client.on('connect', function() { //redis链接成功 console.log('redis connect success!'); if (callback) { callback(client); } }); let first = true; client.on('error', function() { //redis链接失败 console.log('redis connect error!'); if (callback && first == true) { first = false; callback(null); } }); }; function hmSet(options, callback) { if (client) { client.hmset(options.apiType, options.apiName, options.total); //redis简单的使用(设置keys的值) } } function hgetAll(keys, callback, isTotal) { if (client) { client.hgetall(keys, function(err, obj) { //redis简单的使用(查询全部keys) }); } } function getApiNumber(res) { //简单计算api调用总数 } module.exports = { hmSet: hmSet, hgetAll: hgetAll, initRedis: initRedis };
基础功能了解差很少以后,重点介绍一下routes.js路由内部的API封装,也是整个demo部署的比较核心部分。外部公开的API以http(GET方式)为主,本次以Socket调用(内部)示例,大致分享一下本身的心得体会。
routes.js
数据库
ejs使用说明须要在server.js入口配置
app.set('views', path.join(__dirname, './views'));
app.set("view engine", "ejs");
express
const express = require('express'); const router = express.Router(); const version = "/v1"; ... router.get('/music', function(request, response) { //监听路由路由/music访问 //console.log(request.query) //模板使用ejs,response须要设置type,不然会以ejs源码展现 response.type('html'); //经常使用模式 response.render(路由模板,回传页面参数) //此时会查找ejs的配置,view/music.ejs response.render('music', { title: '网易云音乐Cloud', keywords:Tools.randomSongs()//随机取一首歌曲名称搜索 }) //在music.ejs模板中能够<%= title %> <%= keywords %> 使用变量 }); /* ** ** 一、搜索歌曲名 ** params[s=歌曲名,type,offset,limit] ** /search?s=大城小爱 ** */ router.get(version + '/search', function(request, response) { //type:1: 单曲, 10: 专辑, 100: 歌手, 1000: 歌单, 1002: 用户, 1004: MV, 1006: 歌词, 1009: 电台, 1014: 视频 //offset : 偏移数量,用于分页 , 如 : 如 :( 页数 -1)*20, 其中20为limit的值,默认为0 var data = { s: decodeURI(request.query.s) || '', offset: request.query.offset || 0, limit: request.query.limit || 20, type: request.query.type || 1 }; var params = { path: '/weapi/cloudsearch/get/web', request: request, response: response, data: data, apiType: '1' }; //在WebAPI内部response.send响应web数据 Tools.WebAPI(params) }); ... module.exports = router;
而后将router.js挂载在server.js下,整个已配置的路由即可以访问
demo刚开始使用koa2做为服务端的框架,后续由于router.get(xx,function(request, response) { 内部response异步响应很差处理(初学者才疏学浅,很是抱歉,能够一块儿探讨),改用express处理异步响应。})
json
网易云API的请求访问方式,能够抓包或者网易云音乐官网搜索慢慢摸索查看,固然也能够借鉴别人的劳动成果!
心得体会编写中