Best JavaScript code snippet using devicefarmer-stf
app.js
Source:app.js
1var express = require('express');2var path = require('path');3var favicon = require('serve-favicon');4var logger = require('morgan');5var cookieParser = require('cookie-parser');6var bodyParser = require('body-parser');7const axios = require('axios');8var request = require('superagent');9var index = require('./routes/index');10var users = require('./routes/users');11var home = require('./routes/home');12var reactspa = require('./routes/spa');13var cheerio = require('cheerio');14var rlencode = require('urlencode');15var app = express();16// view engine setup17app.set('views', path.join(__dirname, 'views'));18app.set('view engine', 'ejs');19// app.use(express.static(path.join(__dirname, 'public'),{20// maxAge:021// }));22// uncomment after placing your favicon in /public23//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));24app.use(logger('dev'));25app.use(bodyParser.json());26app.use(bodyParser.urlencoded({27 extended: false28}));29app.use(cookieParser());30app.use(express.static(path.join(__dirname, 'public/Portfolio-page'), {31 maxAge: 86400032}));33// app.all("*", (req, res, next) => { 34// let host = req.headers.host;35// host = host.replace(/\:\d+$/, ''); // Remove port number36// res.redirect(307, `https://${host}${req.path}`);37// });38app.use('/', index);39// app.use(express.static(path.join(__dirname, 'public/home'),{40// maxAge:86400041// }));42// app.use('/home', home);43// app.use(express.static(path.join(__dirname, 'public'),{44// maxAge:86400045// }));46// app.use('/reactspa',reactspa);47// app.get('/drrr',(req,res)=>{48// res.sendFile(__dirname+'/public/client/index.html')49// })50app.get('/allbuslist/services/api/monitor/monitorStatus', (req, res, next) => {51 let arr = {52 resultCode:0,53 WIState:'ok',54 clientIP:'127.0.0.1'55 }56 console.log(arr)57 res.json(arr);58});59//天æ°æ¥å£60app.get('/weather/:city', (req, res, next) => {61 let city = req.params.city;62 let arr63 axios.get('http://api.jisuapi.com/weather/query?appkey=adfb0e1348ec0adf', {64 params: {65 city: city66 }67 })68 .then(json => {69 arr = json.data70 }).then(() => {71 res.json(arr)72 })73 .catch(err => console.log(err))74});75//è·åå
¨é¨å
¬äº¤å表76app.get('/allbuslist', (req, res, next) => {77 let url = 'https://shanghaicity.openservice.kankanews.com/public/bus';78 axios.get(url).then(json => {79 let d = json.data;80 let $ = cheerio.load(d);81 // console.log(d)82 let list83 $('script').each(function (i, e) {84 // console.log($(this).html())85 if ($(this).html().indexOf('119') > -1) {86 let d = ($(this).html().split('[')[1].split(']')[0]);87 // console.log(eval('('+('['+d+']')+')'))88 // let t = $(this).html().replace(/[\r\n]/g,'').match(/data.*/g)[0].split('=')[1].replace(/\s/g,'');89 // console.log(t)90 list = eval('(' + ('[' + d + ']') + ')') //(t.split('[')[1].split(']')[0]).replace(/\'/g,'').split(',')91 // return;92 }93 })94 //console.log(list,1)95 return list96 }).then((list) => {97 // let fdata = JSON.parse(JSON.stringify(list));98 if (list) {99 res.send({100 allLines: list101 })102 } else {103 res.sendStatus(500)104 }105 }).catch(err => {106 res.sendStatus(500);107 console.log(err)108 })109})110var bba = { 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',111 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',112 'Host': 'shanghaicity.openservice.kankanews.com',113 // Origin:'https://shanghaicity.openservice.kankanews.com',114 'Referer': 'https://shanghaicity.openservice.kankanews.com/public/bus',115 'Upgrade-Insecure-Requests': '1'116};117// var ba = let ba = {118// Accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',119// 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',120// 'Host': 'shanghaicity.openservice.kankanews.com',121// Referer: 'https://shanghaicity.openservice.kankanews.com/public/bus',122// 'Upgrade-Insecure-Requests': 1123// }124//å
¬äº¤ç«ç¹125app.get('/busstop/:sid', (req, res, next) => {126 let sid = req.params.sid;127 // console.log(sid,1)128 let data = {}129 let url = `https://shanghaicity.openservice.kankanews.com/public/bus/mes/sid/${sid}`130// let bba = { 'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',131// 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',132// 'Host': 'shanghaicity.openservice.kankanews.com',133// // Origin:'https://shanghaicity.openservice.kankanews.com',134// 'Referer': 'https://shanghaicity.openservice.kankanews.com/public/bus',135// 'Upgrade-Insecure-Requests': '1'136// }137 request.get(url).set(bba).then((jsonR) => {138// axios.get(url, {139 // url:url,140 // responseType:'text',141// headers: { Accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',142// 'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; de-de) AppleWebKit/534.15+ (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4',143// 'Host': 'shanghaicity.openservice.kankanews.com'144// }145// })146// .then(json => {147// console.log(jsonR)148 let arr = jsonR.text149 let $ = cheerio.load(arr);150 let start_stop = $('.upgoing p span').first().text().trim();151// console.log(start_stop)152// if (!start_stop) {153// res.sendStatus(500)154// return start_stop155// }156 let end_stop = $('.upgoing p span').eq(1).text().trim();157 // console.log(end_stop,123)158 let start_earlytime = $('.upgoing .time .s').first().text().trim();159 let start_latetime = $('.upgoing .time .m').first().text().trim();160 let end_earlytime = $('.upgoing .time .s').eq(1).text().trim();161 let end_latetime = $('.upgoing .time .m').eq(1).text().trim();162 let busLine = {163 start_stop,164 end_stop,165 start_earlytime,166 start_latetime,167 end_earlytime,168 end_latetime169 };170 let stops = []171 $('div .station .name').each(function (i, e) {172 stops[i] = {173 zdmc: $(this).text().trim(),174 id: 'chou' + i175 }176 })177 let lineResults0 = {178 direction: true,179 stops180 };181 data = {182 busLine,183 lineResults0184 };185 let u1 = `https://shanghaicity.openservice.kankanews.com/public/bus/mes/sid/${sid}?stoptype=1`186// let ba = {187// Accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',188// 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36',189// 'Host': 'shanghaicity.openservice.kankanews.com',190// Referer: 'https://shanghaicity.openservice.kankanews.com/public/bus',191// 'Upgrade-Insecure-Requests': 1192// }193 request.get(u1).set(bba).end((err,resd) => {194// console.log(resd)195 let $ = cheerio.load(resd.text);196 let stops = []197 $('div .station .name').each(function (i, e) {198 stops[i] = {199 zdmc: $(this).text().trim(),200 id: 'chou' + i201 }202 })203 let lineResults1 = {204 direction: false,205 stops206 };207 data = { ...data,208 lineResults1209 };210 let fdata = JSON.parse(JSON.stringify(data));211 if (!fdata) {212 res.sendStatus(500);213 return214 }215 res.json(fdata)216 })217// .then(() => {218 // if(!start_stop){219 // res.send(500)220 // return221 // }222// let u1 = `https://shanghaicity.openservice.kankanews.com/public/bus/mes/sid/${sid}?stoptype=1`223// let ba = {224// Accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',225// 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',226// 'Host': 'shanghaicity.openservice.kankanews.com',227// 'Upgrade-Insecure-Requests': 1228// }229// request.get(u1).set(ba).end((err,resd) => {230// console.log(resd)231// let $ = cheerio.load(resd.data);232// let stops = []233// $('div .station .name').each(function (i, e) {234// 235// stops[i] = {236// zdmc: $(this).text().trim(),237// id: 'chou' + i238// }239// })240// let lineResults1 = {241// direction: false,242// stops243// };244// data = { ...data,245// lineResults1246// };247// let fdata = JSON.parse(JSON.stringify(data));248// if (!fdata) {249// res.sendStatus(500);250// return251// }252// res.json(fdata)253// })254// .then(() => {255// // console.log(data)256// let fdata = JSON.parse(JSON.stringify(data));257// if (!fdata) {258// res.sendStatus(500);259// return260// }261// res.json(fdata)262// })263// .catch(err => {264// res.sendStatus(500);265// console.log(err)266// })267// axios.get(u1, {268// Accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',269// 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1',270// 'Host': 'shanghaicity.openservice.kankanews.com',271// 'Upgrade-Insecure-Requests': 1272// })273// .then(resd => {274// let $ = cheerio.load(resd.data);275// let stops = []276// $('div .station .name').each(function (i, e) {277// stops[i] = {278// zdmc: $(this).text().trim(),279// id: 'chou' + i280// }281// })282// let lineResults1 = {283// direction: false,284// stops285// };286// data = { ...data,287// lineResults1288// };289// }).then(() => {290// // console.log(data)291// let fdata = JSON.parse(JSON.stringify(data));292// if (!fdata) {293// res.sendStatus(500);294// return295// }296// res.json(fdata)297// }).catch(err => {298// res.sendStatus(500);299// console.log(err)300// })301 })302 .catch(err => {303 res.sendStatus(500);304 console.log(err)305 })306});307//å
¬äº¤åæ¥è¯¢id308var base1 = {309 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',310 'Accept-Encoding': 'gzip, deflate, br',311 'Accept-Language': 'zh-CN,zh;q=0.9',312 'Cache-Control':'no-cache',313// 'Connection': 'keep-alive',314// 'Content-Length': 42,315 ':authority': 'shanghaicity.openservice.kankanews.com',316 ':method': 'GET',317':path': '/public/bus',318':scheme': 'https',319 'sec-fetch-dest': 'document',320'sec-fetch-mode': 'navigate',321'sec-fetch-site': 'none',322'sec-fetch-user': '?1',323 'upgrade-insecure-requests': '1',324 // 'Host': 'shanghaicity.openservice.kankanews.com',325 // Origin: 'https://shanghaicity.openservice.kankanews.com',326 //'Referer': 'https://shanghaicity.openservice.kankanews.com/public/bus',327 // Pragma:'no-cache',328 // Host:'shanghaicity.openservice.kankanews.com',329 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Mobile/14F89 MicroMessenger/6.5.10 NetType/WIFI Language/zh_CN',330// 'X-Requested-With': 'XMLHttpRequest'331 }332app.get('/busname/:name', (req, res, next) => {333 var name = req.params.name;//.split('%').length===1?req.params.name.split('%')[0]:req.params.name.split('%')[0]+'è·¯';334// let name = rlencode.parse(âidnum:â+req.params.name, {charset: 'utf-8'});335// var aname = rlencode(name, 'utf-8');336 console.log(name);337// console.log(rlencode(name, 'utf8'));338// console.log( rlencode.decode(aname, 'utf-8')); 339// let base1 = {340// // 'Accept': '*/*',341// // 'Accept-Encoding': 'gzip, deflate, br',342// // 'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',343// // 'Cache-Control':'no-cache',344// // 'Connection': 'keep-alive',345// // 'Content-Length': 42,346// // 'Host': 'shanghaicity.openservice.kankanews.com',347// // Origin: 'https://shanghaicity.openservice.kankanews.com',348// // 'Referer': 'https://shanghaicity.openservice.kankanews.com/public/bus',349// // Pragma:'no-cache',350// // Host:'shanghaicity.openservice.kankanews.com',351// 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_2 like Mac OS X) AppleWebKit/603.2.4 (KHTML, like Gecko) Mobile/14F89 MicroMessenger/6.5.10 NetType/WIFI Language/zh_CN',352// // 'X-Requested-With': 'XMLHttpRequest'353// }354// .type("form")355 request.get('https://shanghaicity.openservice.kankanews.com/public/bus')356 .set(base1)357 .end((err, response) => {358 console.log(response,123)359 if (err) {360 res.sendStatus(500);361 return next(err);362 }363 // let c1 = response.headers['set-cookie'].join(',').match(/(acw_tc=.+?);/)[1];364 console.log(response.headers['set-cookie'],999)365 let c2 = response.headers['set-cookie'].join(',');366 // console.log(c2);367 request.post('https://shanghaicity.openservice.kankanews.com/public/bus/get')368 .set(base1)369 .set('Cookie', c2)370 .type("form")371 .send({ idnum:name})372 .then((resp) => {373 // console.log(resp)374// if (err) {375// res.sendStatus(500);376// return next(err);377// }378// console.log(resp)379// arr = resp.data;380 if (!resp.text) {381 res.sendStatus(500);382 return383 }384 385 res.json(JSON.parse(resp.text))386 }).catch(err=>{console.log(err)})387 })388// request.post('https://shanghaicity.openservice.kankanews.com/public/bus/get').set(base1).type('form').send({ idnum:name}).then((resp) => {389// console.log(resp)390// // if (err) {391// // res.sendStatus(500);392// // return next(err);393// // }394// // console.log(resp)395// // arr = resp.data;396// if (!resp.text) {397// res.sendStatus(500);398// return399// }400 401// res.json(JSON.parse(resp.text))402// }).catch(err=>{console.log(err)})403})404 var baseH = {405 Accept: '*/*',406 'Accept-Encoding': 'gzip, deflate',407 'Accept-Language': 'zh-CN,zh;q=0.9',408 Connection: 'keep-alive',409 'Content-Length': 57,410 Host: 'shanghaicity.openservice.kankanews.com',411 Origin: 'https://shanghaicity.openservice.kankanews.com',412 Referer: 'https://shanghaicity.openservice.kankanews.com/',413 'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; de-de) AppleWebKit/534.15+ (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4',414 'X-Requested-With': 'XMLHttpRequest'415 }416 var baseH1 = {417 Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',418 'Accept-Encoding': 'gzip, deflate',419 'Accept-Language': 'zh-CN,zh;q=0.9',420 Connection: 'keep-alive',421 Referer: 'https://shanghaicity.openservice.kankanews.com/',422 Host: 'shanghaicity.openservice.kankanews.com',423 'Upgrade-Insecure-Requests': 1,424 'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; de-de) AppleWebKit/534.15+ (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4'425 }426 //è·ååå¾åç±»427// var garbageBase = {428// Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',429// 'Accept-Encoding': 'gzip, deflate',430// 'Accept-Language': 'zh-CN,zh;q=0.9',431// Host:'weixin.sh-service.com',432// Referer: 'http://weixin.sh-service.com/sites/feiguan/trashTypes_2/TrashQuery.aspx',433// 'Upgrade-Insecure-Requests': 1,434// 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'435// }436app.get('/searchGarbage/:search',(req,res,next)=>{437 438 let search = req.params.search;439 var str =encodeURI(search);440// console.log(str)441 let url = 'http://trash.lhsr.cn/sites/feiguan/trashTypes_3/TrashQuery.aspx'442 let url1 = 'http://trash.lhsr.cn/sites/feiguan/trashTypes_3/TrashQuery.aspx?kw='+str443// console.log(url1)444// var garbageBase1 = {445// Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',446// 'Accept-Encoding': 'gzip, deflate',447// 'Accept-Language': 'zh-CN,zh;q=0.9',448// Host:'weixin.sh-service.com',449// Referer:url1,450// 'Upgrade-Insecure-Requests': 1,451// 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'452// }453 request.get(url).end((error,respo)=>{454 let c1 = respo.headers['set-cookie'].join(',').match(/(ASP.NET_SessionId=.+?);/)[1];455 request.get(url1).set('Cookie', c1).end((err,resp)=>{456 let arr = resp.text457 let $ = cheerio.load(arr);458 console.log(arr)459 let listaa460 $('script').each(function (i, e) {461 // console.log($(this).html())462 if ($(this).html().indexOf(req.params.search) > -1) {463 let d = ($(this).html().split('(')[1].split(')')[0]);464 // console.log(eval('('+('['+d+']')+')'))465 // let t = $(this).html().replace(/[\r\n]/g,'').match(/data.*/g)[0].split('=')[1].replace(/\s/g,'');466 console.log(d)467 listaa = eval('(' + ('[' + d + ']') + ')') //(t.split('[')[1].split(']')[0]).replace(/\'/g,'').split(',')468 // return;469 }470 })471 console.log(listaa)472 let title = listaa[1];//$('#rm_typekey').eq(0).text().trim();473 let content = listaa[6]//$('#rm_note_1').eq(0).text().trim();474 let desc = listaa[6]//$('#rm_note_1').eq(0).text().trim();475// let li = $('.kp2 ul li').join(',').text().trim();476 let li =[]477 $('.kp2 ul li').each(function(i, elem){478 li[i]= $(this).text();});479let list = li.join(', ');480// console.log(title,content,desc,list)481 if (err) {482 res.sendStatus(500);483 return next(err);484 }485 let d = {486 title,content,desc,list487 }488 let fdata = JSON.parse(JSON.stringify(d));489 if (!fdata) {490 res.sendStatus(500);491 return492 }493 res.json(fdata)494 })495 496 })497 })498//å
¬äº¤æ¥å£æ¥è¯¢å®æ¶499app.get('/bus/:sid/:direction/:stopId', (req, res, next) => {500 let sid = req.params.sid;501 let direction = req.params.direction;502 let stopId = req.params.stopId;503 let arr;504 let para = {505 stoptype: direction,506 stopid: stopId,507 sid: sid508 }509 let ref = `https://shanghaicity.openservice.kankanews.com/public/bus/mes/sid/${sid}`510// let baseH = {511// Accept: '*/*',512// 'Accept-Encoding': 'gzip, deflate',513// 'Accept-Language': 'zh-CN,zh;q=0.9',514// Connection: 'keep-alive',515// 'Content-Length': 57,516// Host: 'shanghaicity.openservice.kankanews.com',517// Origin: 'https://shanghaicity.openservice.kankanews.com',518// Referer: ref,519// 'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; de-de) AppleWebKit/534.15+ (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4',520// 'X-Requested-With': 'XMLHttpRequest'521// }522// let base1 = {523// Accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',524// 'Accept-Encoding': 'gzip, deflate',525// 'Accept-Language': 'zh-CN,zh;q=0.9',526// Connection: 'keep-alive',527// Referer: 'https://shanghaicity.openservice.kankanews.com/',528// Host: 'shanghaicity.openservice.kankanews.com',529// 'Upgrade-Insecure-Requests': 1,530// 'User-Agent': 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; de-de) AppleWebKit/534.15+ (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4'531// }532 request.get('https://shanghaicity.openservice.kankanews.com/public/bus')533 .set(baseH1)534 .end((err, response) => {535 if (err) {536 res.sendStatus(500);537 return next(err);538 }539 let c1 = response.headers['set-cookie'].join(',')//.match(/(acw_tc=.+?);/)[1];540 // console.log(c1);541 request.post('https://shanghaicity.openservice.kankanews.com/public/bus/Getstop')542 .set(baseH)543 .set('Cookie', c1)544 .type("form")545 .send(para)546 .end((err, json) => {547 // å¤çæ°æ®548 // console.log(json)549 if (err) {550 res.sendStatus(500);551 return next(err);552 }553 arr = JSON.parse(json.text);554 if (!arr) {555 res.sendStatus(500);556 return557 }558 res.json(arr)559 })560 })561 // let base1 = {562 // Accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',563 // 'Accept-Encoding':'gzip, deflate',564 // 'Accept-Language':'zh-CN,zh;q=0.9',565 // Connection:'keep-alive',566 // Referer:'http://shanghaicity.openservice.kankanews.com/',567 // Host:'shanghaicity.openservice.kankanews.com',568 // 'Upgrade-Insecure-Requests':1,569 // 'User-Agent':'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; de-de) AppleWebKit/534.15+ (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4'570 // }571 // let base2 = {572 // Accept:'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',573 // 'Accept-Encoding':'gzip, deflate',574 // 'Accept-Language':'zh-CN,zh;q=0.9',575 // 'Cache-Control':'max-age=0',576 // Connection:'keep-alive',577 // Host:'shanghaicity.openservice.kankanews.com',578 // 'Upgrade-Insecure-Requests':1,579 // 'User-Agent':'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_5; de-de) AppleWebKit/534.15+ (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4'580 // }581 // let c1,c2,c3,c4,c5;582 // request.get('https://hm.baidu.com/hm.gif?cc=0&ck=1&cl=24-bit&ds=375x667&vl=667&et=0&ja=0&ln=zh-cn&lo=0<=1524620683&rnd=719889793&si=6f69830ae7173059e935b61372431b35&v=1.2.30&lv=3&ct=!!&tt=%E4%B8%8A%E6%B5%B7%E5%8F%91%E5%B8%83-%E5%B8%82%E6%94%BF%E5%A4%A7%E5%8E%85&sn=34872')583 // .end((err,hr)=>{584 // if (err) {585 // return next(err);586 // }587 // c1 = hr.headers['set-cookie'].join(',').match(/(HMACCOUNT=.+?);/)[1];588 // //console.log(hr);589 // //console.log(c1);590 // request.get('http://shanghaicity.openservice.kankanews.com')591 // .set(base2)592 // .end((err,hrr)=>{593 // if (err) {594 // return next(err);595 // }596 // //console.log(hrr.headers['set-cookie'])597 // c2 = hrr.headers['set-cookie'].join(',').match(/(Hm_1vt_6f69830ae7173059e935b61372431b35=.+?);/)[1];598 // c4 = 'Hm_lvt_6f69830ae7173059e935b61372431b35=1524617432,1524617445,1524619410,1524620683';599 // c5 = 'Hm_lpvt_6f69830ae7173059e935b61372431b35='+new Date().valueOf();600 // //console.log(c2);601 // c3 = c1+'; '+c2+ '; _gat=1';602 // //console.log(c3);603 // request.get('http://shanghaicity.openservice.kankanews.com/public/bus')604 // .set(base1)605 // .set('Cookie',c3)606 // .end((err,response)=>{607 // if (err) {608 // return next(err);609 // }610 // let cook = response.headers['set-cookie'].join(',');611 // let cookie1 = cook.match(/(HA=.+?);/)[1];612 // let cookie2 =cook.match(/(HA=.+?);/)[1];613 // let cookie3 =cook.match(/(HB=.+?);/)[1];614 // let cookie4 =cook.match(/(HC=.+?);/)[1];615 // let cookie5 =cook.match(/(HD=.+?);/)[1];616 // let cookie6 =cook.match(/(HG=.+?);/)[1];617 // let cookie7 =cook.match(/(HH=.+?);/)[1];618 // let cookie8 =cook.match(/(HK=.+?);/)[1];619 // let cookie9 =cook.match(/(HO=.+?);/)[1];620 // let cookie10 =cook.match(/(HY=.+?);/)[1];621 // let cookie14 =cook.match(/(Hm_p1vt_6f69830ae7173059e935b61372431b35=.+?);/)[1];622 // let fin = [cookie1,cookie2,cookie3,cookie4,cookie5,cookie6,cookie7,cookie8,cookie9,cookie10,c2,c4,c5,cookie14]623 // let finC = fin.join('; ');624 // request.post('http://shanghaicity.openservice.kankanews.com/public/bus/Getstop')625 // .set(baseH)626 // .set('Cookie',finC)627 // .type("form")628 // .send(para)629 // .end((err,json) => {630 // // å¤çæ°æ®631 // // console.log(json)632 // if (err) {633 // return next(err);634 // }635 // arr = JSON.parse(json.text);636 // res.json(arr)637 // })638 // })639 // }) 640 // })641});642//çµå½±è¯¦ç»643app.get('/movie/subject/:id', (req, res, next) => {644 let id = req.params.id;645 let arr646 // console.log(type)647 axios.get(`https://douban.uieee.com/v2/movie/subject/${id}`)648 .then(json => {649 // console.log(json)650 arr = json.data651 }).then(() => {652 res.json(arr)653 })654 .catch(err => console.log(err))655});656//çµå½±657app.get('/movie/:type', (req, res, next) => {658 let type = req.params.type;659 let start = req.query.start;660 let count = req.query.count;661 let city = req.query.city;662 let arr663 // console.log(type)664 axios.get(`https://douban.uieee.com/v2/movie/${type}`, {665 params: {666 start: start,667 count: count,668 city: city669 }670 })671 .then(json => {672 // console.log(json)673 arr = json.data674 }).then(() => {675 res.json(arr)676 })677 .catch(err => console.log(err))678});679//æ座è¿å¿680app.get('/astro/fortune/:astroid', (req, res, next) => {681 let astroid = req.params.astroid;682 let arr683 axios.get('http://api.jisuapi.com/astro/fortune?appkey=adfb0e1348ec0adf', {684 params: {685 astroid: astroid686 }687 })688 .then(json => {689 arr = json.data690 }).then(() => {691 res.json(arr)692 })693 .catch(err => console.log(err))694});695// catch 404 and forward to error handler696app.use(function (req, res, next) {697 var err = new Error('Not Found');698 err.status = 404;699 next(err);700});701// error handler702app.use(function (err, req, res, next) {703 // set locals, only providing error in development704 res.locals.message = err.message;705 res.locals.error = req.app.get('env') === 'development' ? err : {};706 // render the error page707 res.status(err.status || 500);708 res.render('error');709});...
OpenService.js
Source:OpenService.js
1openService= {2 openServiceAPIURL: "http://123.57.32.46:8080/openServiceAPI?",3 scriptURL: "http://123.57.32.46:8080/plugins/",4 authedServices:[],5 unauthedServices:[],6 pluginNum:0,7 afterInit: function(){8 $.get(openService.openServiceAPIURL, {9 action : 'services',10 userid : userid11 }, function(data) {12 var toolbar = $('#toolbar');13 toolbar.append($("<div/>").attr("id", "ToolsMenu"));14 var sevlist =$.parseJSON(data);15 openService.authedServices = sevlist;16 dialog.delPlugin.flushTable();17 for (i in openService.authedServices) {18 var serviceName = openService.authedServices[i].serviceName;19 var ownerName = openService.authedServices[i].ownerName;20 jQuery.getScript(openService.scriptURL+ownerName+"/"+serviceName+"/"+serviceName+".js")21 .done(function() { 22 openService.pluginNum++;23 if(openService.pluginNum== openService.authedServices.length){24 openService.initToolbarButton();25 }26 27 28 29 });30 31 }32 if(openService.authedServices.length==0)33 openService.initToolbarButton();34 35 36 37 });38 $.get(openService.openServiceAPIURL, {39 action : 'unauthedservices',40 userid : userid41 }, function(data) {42 openService.unauthedServices = $.parseJSON(data);43 dialog.addPlugin.flushTable();44 45 });46 47 48 49 },50 51 authSevIndex: function (sevname) {52 for (var i = 0; i < openService.authedServices.length; i++) {53 var sev = openService.authedServices[i];54 if (sev.serviceName == sevname) {55 return i;56 }57 }58 return openService.authedServices.length;59 },60 61 unauthSevIndex:function (sevname) {62 for (var i = 0; i < openService.unauthedServices.length; i++) {63 var sev = openService.unauthedServices[i];64 if (sev.serviceName == sevname) {65 return i;66 }67 }68 return openService.unauthedServices.length;69 },70 71 getClassesPath: function(){72 return "/data/workspace/javaweb/"+ownername+"/"+appname+"/target/classes/";73 },74 75 initWorkSpace: function(userName, serviceName){76 $.post(openService.openServiceAPIURL, {77 action: 'initWorkSpace',78 apptype: apptype,79 appowner: ownername,80 appname: appname,81 serviceowner: userName,82 servicename: serviceName83 }, function(data){84 85 86 });87 },88 89 initToolbarButton: function(){90 91 var ToolsMB= $("#ToolsMB");92 var ToolsMenu = $("#ToolsMenu");93 var findbugs = $("<div/>").attr("id", "findbugs").html("findbugs").bind('click', function(){94 95 var url = Global.url.findbugs;96 var param = {97 filepath: "/data/repo/javaweb/"+ownername+"/"+appname+"/target/classes/"98 99 };100 var success = function(data){101 consolePanel.append('info', 'FindBugs', data);102 103 };104 $.post(url, param, success);105 });106 var checkstyle = $("<div/>").attr("id", "checkstyle").html("checkstyle").bind('click', function(){107 108 var url = Global.url.checkstyle;109 var param = {110 filepath: "/data/repo/javaweb/"+ownername+"/"+appname+"/src/main/"111 112 };113 var success = function(data){114 consolePanel.append('info', 'Checkstyle', data);115 116 };117 $.post(url, param, success);118 });119 var addPlugin = $("<div/>").attr("id", "addPlugin").html("install plugin").bind('click',120 function(){121 122 //dialog.addPlugin.flushTable();123 $('#addPluginDialog').dialog("open");124 });125 var delPlugin= $("<div/>").attr("id", "delPlugin").html("uninstall plugin").bind('click',126 function(){127 $('#delPluginDialog').dialog("open");128 129 });130 ToolsMenu.append(findbugs,checkstyle,$("<div class='menu-sep'></div>"),addPlugin,delPlugin);131 ToolsMB.menubutton({132 menu: "#ToolsMenu"133 });134 135 },136 137 ...
open.ts
Source:open.ts
1import { Router, Request, Response, NextFunction } from 'express';2import { Container } from 'typedi';3import OpenService from '../services/open';4import { Logger } from 'winston';5import { celebrate, Joi } from 'celebrate';6const route = Router();7export default (app: Router) => {8 app.use('/', route);9 route.get(10 '/apps',11 async (req: Request, res: Response, next: NextFunction) => {12 const logger: Logger = Container.get('logger');13 try {14 const openService = Container.get(OpenService);15 const data = await openService.list();16 return res.send({ code: 200, data });17 } catch (e) {18 return next(e);19 }20 },21 );22 route.post(23 '/apps',24 celebrate({25 body: Joi.object({26 name: Joi.string().optional().allow('').disallow('system'),27 scopes: Joi.array().items(Joi.string().required()),28 }),29 }),30 async (req: Request, res: Response, next: NextFunction) => {31 const logger: Logger = Container.get('logger');32 try {33 const openService = Container.get(OpenService);34 const data = await openService.create(req.body);35 return res.send({ code: 200, data });36 } catch (e) {37 return next(e);38 }39 },40 );41 route.put(42 '/apps',43 celebrate({44 body: Joi.object({45 name: Joi.string().optional().allow(''),46 scopes: Joi.array().items(Joi.string()),47 id: Joi.number().required(),48 }),49 }),50 async (req: Request, res: Response, next: NextFunction) => {51 const logger: Logger = Container.get('logger');52 try {53 const openService = Container.get(OpenService);54 const data = await openService.update(req.body);55 return res.send({ code: 200, data });56 } catch (e) {57 return next(e);58 }59 },60 );61 route.delete(62 '/apps',63 celebrate({64 body: Joi.array().items(Joi.number().required()),65 }),66 async (req: Request, res: Response, next: NextFunction) => {67 const logger: Logger = Container.get('logger');68 try {69 const openService = Container.get(OpenService);70 const data = await openService.remove(req.body);71 return res.send({ code: 200, data });72 } catch (e) {73 return next(e);74 }75 },76 );77 route.put(78 '/apps/:id/reset-secret',79 celebrate({80 params: Joi.object({81 id: Joi.number().required(),82 }),83 }),84 async (req: Request<{ id: number }>, res: Response, next: NextFunction) => {85 const logger: Logger = Container.get('logger');86 try {87 const openService = Container.get(OpenService);88 const data = await openService.resetSecret(req.params.id);89 return res.send({ code: 200, data });90 } catch (e) {91 return next(e);92 }93 },94 );95 route.get(96 '/auth/token',97 celebrate({98 query: {99 client_id: Joi.string().required(),100 client_secret: Joi.string().required(),101 },102 }),103 async (req: Request, res: Response, next: NextFunction) => {104 const logger: Logger = Container.get('logger');105 try {106 const openService = Container.get(OpenService);107 const result = await openService.authToken(req.query as any);108 return res.send(result);109 } catch (e) {110 return next(e);111 }112 },113 );...
Using AI Code Generation
1var stf = require('devicefarmer-stf-client');2var client = new stf();3 if (err) {4 console.log('Error opening service: ' + err);5 } else {6 console.log('Service opened');7 }8});9var stf = require('devicefarmer-stf-client');10var client = new stf();11 if (err) {12 console.log('Error opening service: ' + err);13 } else {14 console.log('Service opened');15 client.getDevices(function (err, devices) {16 if (err) {17 console.log('Error getting devices: ' + err);18 } else {19 console.log(devices);20 }21 });22 }23});24[ { serial: '0123456789ABCDEF',25 network: { wifi: false, type: 'none' },26 battery: { present: false, level: null, scale: null, status: null, health: null, source: null, voltage: null, temperature: null, technology: null },27 display: { id: 0, width: 0, height: 0, xdpi: 0, ydpi: 0, fps: 0, density: 0, rotation: 0, secure: false, size: 0, url: null },28 phone: { id: 0, name: null, product: null, device: null, model: null, brand: null, manufacturer: null, board: null, bootloader: null, hardware: null, serial: null, abi: null, abi2
Using AI Code Generation
1var service = require('devicefarmer-stf-service');2service.openService(function(err, result) {3 console.log('result', result);4});5var service = require('devicefarmer-stf-service');6service.closeService(function(err, result) {7 console.log('result', result);8});9var service = require('devicefarmer-stf-service');10service.restartService(function(err, result) {11 console.log('result', result);12});13var service = require('devicefarmer-stf-service');14service.getServiceStatus(function(err, result) {15 console.log('result', result);16});
Using AI Code Generation
1var stfService = require('devicefarmer-stf-service');2service.getDevices(function (err, devices) {3 console.log("Devices: " + JSON.stringify(devices));4});5var stfService = require('devicefarmer-stf-service');6service.getDevices(function (err, devices) {7 console.log("Devices: " + JSON.stringify(devices));8});9var stfService = require('devicefarmer-stf-service');10service.getDevices(function (err, devices) {11 console.log("Devices: " + JSON.stringify(devices));12});13var stfService = require('devicefarmer-stf-service');14service.getDevices(function (err, devices) {15 console.log("Devices: " + JSON.stringify(devices));16});17var stfService = require('devicefarmer-stf-service');18service.getDevices(function (err, devices) {19 console.log("Devices: " + JSON.stringify(devices));20});21var stfService = require('devicefarmer-stf-service');22service.getDevices(function (err, devices) {23 console.log("Devices: " + JSON.stringify(devices));24});25var stfService = require('devicefarmer-st
Using AI Code Generation
1var openService = require('devicefarmer-stf-client').openService;2var service = openService('wifi', function(err, service){3 if(err){4 console.log(err);5 }6 else{7 service.startService(function(err, status){8 if(err){9 console.log(err);10 }11 else{12 console.log(status);13 setTimeout(function(){14 service.stopService(function(err, status){15 if(err){16 console.log(err);17 }18 else{19 console.log(status);20 }21 });22 }, 5000);23 }24 });25 }26});27setTimeout(function(){28 service.stopService(function(err, status){29 if(err){30 console.log(err);31 }32 else{33 console.log(status);34 }35 });36}, 10000);37setTimeout(function(){38 service.stopService(function(err, status){39 if(err){40 console.log(err);41 }42 else{43 console.log(status);44 }45 });46}, 15000);47setTimeout(function(){48 service.stopService(function(err, status){49 if(err){50 console.log(err);51 }52 else{53 console.log(status);54 }55 });56}, 20000);57setTimeout(function(){58 service.stopService(function(err, status){59 if(err){60 console.log(err);61 }62 else{63 console.log(status);64 }65 });66}, 25000);67setTimeout(function(){68 service.stopService(function(err, status){69 if(err){70 console.log(err);71 }72 else{73 console.log(status);74 }75 });76}, 30000);77setTimeout(function(){78 service.stopService(function(err, status){79 if(err){80 console.log(err);81 }82 else{83 console.log(status);84 }85 });86}, 35000);
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!