hope someone can help me. I'm trying to deploy a web app on netlify, but i don't know how to call the API the right way, providing the right value.
this is my netlify function file:
const fetch = require('node-fetch');
exports.handler = async event => {
const API_KEY = process.env.API_KEY;
const response = await fetch(`https://api.waqi.info/feed/${process.env.CITY}/?token=${API_KEY}`);
const data = await response.json();
const pass = (body) => {
return {
statusCode: 200,
body: JSON.stringify(body)
}
};
return pass(data);
}
My problem is about providing the right city
value to the API call.
i've also tried to make city
an env var on netlify, but even if i change its value, the file lambda.js provides me always the same value probably because it runs just one time at the start.
Here's the code in index.js
:
let CITY = process.env.CITY;
async function getCityPollution(city) {
let response = await fetch("/.netlify/functions/lambda");
let result = await response.json();
if(response.status == 200 && result.status == 'ok') {
await dataHandler(result);
console.log(result);
} else if (result.status == 'error'){
console.log(`${result.status}: ${result.data}`);
setTimeout(() => {
dataParagraph.innerHTML = `Unfortunately we have no datas for ${city} station (incredible but true),
insert coords to check datas from the nearest station or try with another city.
Go check <a href="https://waqi.info/">https://waqi.info/</a> to see our coverage`;
$("html, body").animate({ scrollTop: document.body.scrollHeight }, "slow");
}
, 50);
} else {
console.log(response.status);
}
}
// getting city input and call output function
let getCity = document.querySelector('#getCity');
getCity.onclick = async () => {
CITY = cityInput.value;
if (!CITY) {
emptyFields(cityInput);
} else {
await getCityPollution(CITY);
coordInput[0].value = '';
coordInput[1].value = '';
console.log(CITY) //it works, the value changes
}
}
Obviously this is the try with the netlify env var. This way i get always the same value. There's a way to pass the right value of CITY everytime i need it? Even without using env variables.
Thank you in advance