import fetch from'node-fetch-npm';// 获取fromCurren国家到toCurren国家货币的汇率,货币输入如GBP\\EURasyncfunctionGetConvert(fromCurren1, toCurren1, amount1)let toCurren = toCurren1;let fromCurren = fromCurren1;let amount = amount1;//这是每次请求API都要有的const headers1 =newfetch.Headers('Content-Type':'application/json');//这是每次请求API都要有的
headers1.append("apikey","6jxKy8i7RSajhm8A我的密钥HKOatvYI我赌没人看我的密钥和文章xIbiSQh4");var requestOptions =method:'GET',redirect:'follow',headers: headers1
;const response =awaitfetch(`https://api.我赌没人看我的密钥和文章apilayer.com/exch我的密钥angerates_data/convert?to=$toCurren&from=$fromCurren&amount=$amount`, requestOptions);const result =await response.text();const res =awaitJSON.parse(result).result
if(!res)thrownewError('未获取到汇率!')return res
// GetConvert('GBP','USD',100).then((message) => // console.log(message)// )// 通过2-3个货币字符获取国家全名asyncfunctionGetCountry(CurrentCountry1)let CurrentCountry = CurrentCountry1;const headers1 =newfetch.Headers('Content-Type':'application/json');
headers1.append("apikey","6jxKy8i7RSajhm8我的密钥AHKOatv我赌没人看我的密钥和文章YIxIbiSQh4");var requestOptions =method:'GET',redirect:'follow',headers: headers1
;let res =[]const response =awaitfetch(`https我的密钥://api.apilayer.com/geo/country/我赌没人看我的密钥和文章currency/$CurrentCountry`,requestOptions)// 这里一定要await,不然获取不到数据await response.text()const result =await response.text()const data =JSON.parse(result);for(let i=0; i<data.length; i++)
res.push(data[i].name)// console.log(res)if(res ===[])thrownewError('未获取到国家')return res
// GetCountry('USD').then((message) => // console.log(message)// )//程序入口constConvertCurrency=async(fromCurren, toCurren, amount)=>tryconst exchange =awaitGetConvert(fromCurren, toCurren, amount)const country =awaitGetCountry(toCurren)return`$amount$fromCurren is worth $exchange$toCurren , you can use it in $country`catch(error)
console.log(error)ConvertCurrency('GBP','USD',100).then((message)=>
console.log(message))
可以看到最后输出: 100 GBP is worth 121.775 USD , you can use it in American Samoa,Bonaire, Sint Eustatius and Saba,British Indian Ocean Territory,United States Minor Outlying Islands,Virgin Islands (British),Virgin Islands (U.S.),Cambodia,Ecuador,El Salvador,Guam,Marshall Islands,Micronesia (Federated States of),Northern Mariana Islands,Palau,Panama,Puerto Rico,Timor-Leste,Turks and Caicos Islands,United States of America,Zimbabwe