看看了画在手上的JQuery手表,立刻就快到了下班的时间了,内心总觉的空唠唠的, 好像空缺了什么同样,仔细的想了一想,微微叹了一口气,以为是时候在这里和你们分享一下缘由了........html
首先:git
npm install util npm install https npm install querystring
万成不变,不离其中 引入依赖,顺便设定为严格模式:github
/**设置为严格模式*/ 'use strict'; /** * dependence */ const https = require('https'); const util = require('util'); const querystring = require('querystring');
下面就是重要内容代码块,命名:weather.js(random).npm
/** * Weather. */ const Weather = { /** * url */ url: "https://restapi.amap.com/v3/weather/weatherInfo?%s", /** * API Key */ key: "xxxxxxxxxxxxxxxxxxxxxx", /** * @param string city * @param string format * * @return mixed|string */ getLiveWeather: (city, format = 'json') => { return Weather.getWeather(city, 'base', format); }, /** * @param string city * @param string format * * @return mixed|string */ getForecastsWeather: (city, format = 'json') => { return Weather.getWeather(city, 'all', format); }, /** * @param string city * @param string type * @param string format * * @return mixed|string * * @throws HttpException * @throws InvalidArgumentException */ getWeather: (city, type, format = 'json') => { if (!['base', 'all'].includes(type.toLowerCase())) { console.error('Invalid type value(base/all):', type); return; } if (!['json', 'xml'].includes(format.toLowerCase())) { console.error('Invalid response format(json/xml):', format); return; } let query = querystring.stringify( { key: Weather.key, city: city, output: format.toLowerCase(), extensions: type.toLowerCase() } ); let getUrl = util.format(Weather.url, query); https.get(getUrl, res => { const buffer = []; res.on('data', data => { buffer.push(data); }); res.on('end', () => { let data = Buffer.concat(buffer).toString('utf-8'); console.log("json" === format ? JSON.parse(data) : data); }); }).on('error', err => { console.log(err); }); } }; //暴露接口 module.exports = Weather;
const weather = require('./weather');
而后就能够json
response = weather.getLiveWeather('上海');
response = weather.getForecastsWeather('上海', 'json');
response = weather.getLiveWeather('上海', 'xml');
原文出处:https://www.cnblogs.com/pingtouge/p/11271847.htmlapi