正在尝试对项目的其余部分使用HTTPS Get请求[Node.Js]



我正在尝试使用API获取获取本地城市的IP地址。然后使用城市名称从IP地址运行抛出另一个API,以获得当地天气时,他们访问我的引用。这是我自己尝试的第一个NodeJs项目。我想要一个API调用来获取包含IP地址信息的JSON对象。到目前为止,我只得到了未定义或Promise{pending}。

我查阅了使用async/await函数和使用fetch((函数而不是https的情况。我还尝试过将get请求包装在一个新的Promise函数中,但仍然有未定义的结果。在这个项目中,我有主要的app.js和一个functions.js,试图保持干净的代码。我完全迷路了。

第一次尝试。

function getRawData(){
const https = require('https');
return new Promise((resolve, reject) =>{
https.get('https://api.ipgeolocation.io/ipgeo?apiKey=' + ipApiKey, res => {
console.log('statusCode:', res.statusCode);
res.on('data', d => {
let data = JSON.parse(d);
let cData = data.city
resolve(cData);
}).on('error', e =>{
reject('error'. e.message);
});
});
});

}

function getIp(){
getRawData().then(data =>{
return data;
}).catch(error => {
console.log(error);
});

}

我尝试过一种不同类型的代码:

async function getIPAddress(){
let data = await fetch('https://api.ipgeolocation.io/ipgeo?apiKey=' + ipApiKey)
.then(res => res.json())
.then(res => {return res});
return data;

}

当我调用主应用程序.js上的任何函数时,我都无法获得所需的JSON数据。请帮忙。

我在堆栈调用中使用fetch函数找到了答案。

function requestIP(url){
return fetch(url)
.then(r => r.json())
.then(json => json);
} 
fs.requestIP(ipUrl).then(data =>{
const part ='hourly,alerts,minutely';
const lat = data.lat;
const lon = data.lon;
const name = data.city;
const apiKey = process.env.WEATHER_API_KEY;
const units = "imperial";
const urlWeather = 'https://api.openweathermap.org/data/2.5/onecall?lat=' + lat + '&lon=' + lon + '&units=' + units + '&exclude=' + part + '&appid=' + apiKey;
fetch(urlWeather)
.then(r => r.json())
.then(json =>{
let todayW = json.current;
let tomW = json.daily[0];
let n1Day = json.daily[1];
let n2Day = json.daily[2];
let todayDate = fs.todaysDate();
res.render('home', {               
CR: fs.getCopyRights(), 
dayDate: todayDate,
cityName: name, 
todayT: Math.floor(todayW.temp),
todayI: todayW.weather[0].icon,
tomT: Math.floor(tomW.temp.day),
tomI: tomW.weather[0].icon,
next1T: Math.floor(n1Day.temp.day),
next1I: n1Day.weather[0].icon,                
next2T: Math.floor(n2Day.temp.day),
next2I: n2Day.weather[0].icon,               
});
});
});

相关内容

最新更新