import fetch from 'node-fetch'
// Constants for API details
const GEO_API_URL = 'https://wft-geo-db.p.rapidapi.com/v1/geo/cities';
const WEATHER_API_URL = 'https://weatherbit-v1-mashape.p.rapidapi.com/current';
// Separate headers for the two APIs
const GEO_HEADERS = {
'X-RapidAPI-Host': 'wft-geo-db.p.rapidapi.com',
'X-RapidAPI-Key': '5470f285aemshd79624e8065945cp1df6d3jsn4b3dac9e4d7c'
};
const WEATHER_HEADERS = {
'X-RapidAPI-Host': 'weatherbit-v1-mashape.p.rapidapi.com',
'X-RapidAPI-Key': '5470f285aemshd79624e8065945cp1df6d3jsn4b3dac9e4d7c'
};
const getCityDetails = async (cityId) => {
try {
let response = await fetch(${GEO_API_URL}?cityId=${cityId}, {
method: 'GET',
headers: GEO_HEADERS
});
let data = await response.json();
if(data.data && data.data.length > 0) {
return data.data[0];
} else {
throw new Error('City not found');
}
} catch (error) {
console.error(Error fetching city details: ${error.message});
throw error;
}
};
const getWeatherDetails = async (latitude, longitude) => {
try {
let response = await fetch(${WEATHER_API_URL}?lat=${latitude}&lon=${longitude}, {
method: 'GET',
headers: WEATHER_HEADERS
});
let data = await response.json();
if(data.data && data.data.length > 0) {
return data.data[0];
} else {
throw new Error('Weather data not available');
}
} catch (error) {
console.error(Error fetching weather details: ${error.message});
throw error;
}
};
const getCityAndWeatherInfo = async (cityId) => {
try {
let cityDetails = await getCityDetails(cityId);
let weatherDetails = await getWeatherDetails(cityDetails.latitude, cityDetails.longitude);
return {
population: cityDetails.population,
elevation: cityDetails.elevationMeters,
currentTemperature: weatherDetails.temp
};
} catch (error) {
console.error(Error fetching combined data: ${error.message});
}
};
// Example usage
getCityAndWeatherInfo('Q5465')
.then(data => {
console.log(data);
});
问题如下: 创建一个模块来查找特定城市的当前信息。 可以使用此 API (https://rapidapi.com/wirefreethought/api/geodb-cities/) 查找城市信息,包括坐标。 ● 我们将使用(node.js)Fetch ● 您可以假设该城市始终位于南非。 ● 应显示以下详细信息: Ø 人口 Ø 海拔 o 当前温度(使用此天气 API:https://rapidapi.com/weatherbit/api/weather/) ● 应妥善处理所有潜在错误。
我根据需要订阅了上述内容。
代码中的某些内容不起作用,目前我不知道在哪里再搜索问题。
感谢您的协助。
据我了解,“代码中的某些内容不起作用”的意思是代码未正确编译,对吧?
由于console.error消息,存在编译错误。 您需要使用反引号 `` 在控制台错误消息中使用 ${}。
尝试改变这个:
console.error(获取天气详细信息时出错:${error.message});
对此:
console.log(`获取城市详细信息时出错:${error.message}`);
您可以在这里了解更多信息: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals