const http = require("http"); const url = require("url"); const { ServerModel } = require('./model/ServerModel'); const { SearchModel } = require('./model/SearchModel'); const { SuccessResult, ErrorResult } = require('./model/ResultModel'); const { QQSource } = require('./source/QQSource'); const { MyFreemp3QQSource } = require('./source/MyFreemp3QQSource'); // *********************************************************************** // 注册源 const searcher = new SearchModel(); searcher.registerSourceModel(new QQSource()); searcher.registerSourceModel(new MyFreemp3QQSource()); // *********************************************************************** // 添加API接口 const _server = new ServerModel(); _server.get("/api/source/all", (req, res, query) => { // 罗列都有哪些源 return new SuccessResult(searcher.getSourceList()); }); _server.get("/api/search", async (req, res, query) => { //从源去进行搜索 let result = await searcher.searchMusic(query.source_name, query.keywords); return new SuccessResult(result); }) // *********************************************************************** // 运行服务 const server = http.createServer(async (req, res) => { let method = req.method; let reqUrl = req.url; let reqApi = reqUrl.split('?')[0]; console.log(method); let result; if(method == "GET") { let query = url.parse(reqUrl, true).query; result = await _server.trigger(method, reqApi, req, res, query, null); }else if(method == "POST") { let query = url.parse(reqUrl, true).query; let data = {}; result = await _server.trigger(method, reqApi, req, res, query, data); } res.setHeader('Access-Control-Allow-Origin', '*'); //res.setHeader('Access-Control-Allow-Methods', '*'); res.setHeader('Access-Control-Allow-Headers', '*'); res.setHeader('Content-type', 'application/json;charset=utf-8'); //res.writeHead(200, { 'Content-type': 'application/json;charset=utf-8' }); res.end(JSON.stringify(result)); }); server.listen(5000, () => { console.log("server running at prot 5000"); });