I am trying to retrieve and output weather data from the OpenWeather API, but I am consistently getting the error "Unexpected token o in JSON at position 1". I am using the request module and have written the code as follows:
const request = require('request');
async function getWeatherData(openweather_city_id, openweather_api_key) {
try {
// URL of the OpenWeather API with login information
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?id=${openweather_city_id}&appid=${openweather_api_key}`;
// Retrieve weather data from the OpenWeather API
const weatherResponse = await request(apiUrl, function(error, response, body) {
if (error) {
console.error(error);
} else {
// Parse weather data
const weatherData = JSON.parse(body);
// Loop through weather data and output location name and current temperature
for (let i = 0; i < weatherData.weather.length; i ) {
let weather = weatherData.weather[i];
console.log(`The location is ${weatherData.name} and the current temperature is ${weatherData.main.temp} degrees Celsius.`);
}
}
});
} catch (error) {
console.error(error);
}
}
getWeatherData();
I've already tried running the code without the await keyword and replacing the request module with the Axios module but neither solution worked. Can anyone tell me how to fix this problem?"
CodePudding user response:
To use Async/await it would be easier for you to use Axios library, since it's a promise-based HTTP, it's also easier to read :
const axios = require('axios'); // legacy with common.js
async function getWeatherData(openweather_city_id, openweather_api_key) {
try {
const apiUrl = `https://api.openweathermap.org/data/2.5/weather?id=${openweather_city_id}&appid=${openweather_api_key}`;
const weatherResponse = await axios.get(apiUrl);
const weatherData = weatherResponse.data; //this library will take care for you and parse in json by default in the data property.
if (!weatherData) {
console.error(error);
} else {
for (let i = 0; i < weatherData.weather.length; i ) {
let weather = weatherData.weather[i];
console.log(`The location is ${weather.name} and the current temperature is ${weather.main.temp} degrees Celsius.`);
}
}
}catch (error) {
console.error(error);
}
}
getWeatherData(); // with 2 arguments
you can read their documentation for more detail : https://axios-http.com/docs/intro