希望可以有人帮帮我。我正在尝试在 netlify 上部署一个 Web 应用程序,但我不知道如何以正确的方式调用 API,以提供正确的值。
这是我的 netlify 函数文件:
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);
}
我的问题是为city
API 调用提供正确的值。
我还尝试city
在 netlify 上创建一个 env var,但即使我更改它的值,文件 lambda.js 也始终为我提供相同的值,可能是因为它在一开始只运行一次。
这是中的代码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
}
}
显然,这是对 netlify env var 的尝试。这样我总是得到相同的值。有一种方法可以在我每次需要时传递正确的 CITY 价值吗?即使不使用环境变量。
先感谢您