定义变量及所需配置
const http = require('http'); const url = require('url'); const qs = require('querystring'); const md5 = require("md5"); const config = { sid: 0,//在Mcrmb中你的服务器ID key: "",//通讯密钥 server: { port: 8081,//http服务器运行在什么端口 onlyLocal: true//仅允许本地链接请求 } };
定义类及函数
const MCRMB = function(name, type = "", o2 = {}) { return new Promise(function (resolve, reject) { let o1 = { sign: "", sid: config.sid, wname: name }; let data = Object.assign(o1, o2); data.sign = getSign(data); console.log(data); let options = { hostname: 'api.mcrmb.com', port: 80, path: '/Api/'+type+'?' + qs.stringify(data), method: 'GET', timeout: 3000, headers: { 'User-Agent': 'java request.' } }; let req = http.request(options, function (res, req) { if(res.statusCode != 200) resolve({code: 417, msg: "Incorrect status code."}); res.setEncoding('utf8'); res.on('data', function (chunk) { try{ console.log(JSON.parse(chunk)); } catch(e) { resolve({code: 417, msg: e.message}) } resolve(JSON.parse(chunk)); }); }).on('error', function (e) { console.log('problem with request: ' + e.message); resolve({code: 503, msg: e.message}); }).end(); }); } function getSign(obj, str = "") {//签名算法 for (i in obj) str = str.concat(obj[i]); return md5(str + config.key); }
使用NodeJS搭建服务器
//?name=玩家名&type=api类型&... var Server = http.createServer(async function(req, res) { if(req.url === "/") { res.setHeader("Content-type", "text/html;charst=utf-8"); res.end(fs.readFileSync("./index.html", "utf-8")); } if(req.connection.remoteAddress != "::1" && config.server.onlyLocal) res.end({code: 403, msg: "only local"}); let params = url.parse(req.url, true).query; let name = params.name; let type = params.type; delete params.name; delete params.type; let data = await MCRMB(name, type, params); res.setHeader("Content-type", "text/plain;charst=utf-8"); res.end(JSON.stringify(data)); }).listen(config.server.port, () => { console.log("Server runing at localhost:" + config.server.port); });
全部复制到一个index.js文件后运行,就可以使用 http://localhost:8081/?name=玩家名&type=Cheak 查询玩家数据。
我已在minebbs中发布 [NodeJS] MCrmbAPI 资源。
暂无评论