React JS OpenWeatherMap API Key不在.env中工作,但直接在app.JS中工作



我试图将OpenWeatherMap API密钥放入.env文件中,但当我调用它时,它会控制台记录401错误(未经授权(,当我在没有.env文件的情况下直接在app.js文件中调用时,它能很好地工作。

App.js:

const [currentWeather, setCurrentWeather] = useState(null);
const [forecast, setForecast] = useState(null);
const handleOnSearchChange = (searchData) => {
const [lat, lon] = searchData.value.split(" ");
const currentWeatherFetch = fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_SECRET_KEY}`
);
const forecastFetch = fetch(
`https://api.openweathermap.org/data/2.5/forecast?lat=${lat}&lon=${lon}&appid=${process.env.REACT_APP_SECRET_KEY}`
);
Promise.all([currentWeatherFetch, forecastFetch])
.then(async (response) => {
const weatherResponse = await response[0].json();
const forecastResponse = await response[1].json();
setCurrentWeather({ city: searchData.label, ...weatherResponse });
setForecast({ city: searchData.label, ...forecastResponse });
})
.catch(console.log);
};
console.log(currentWeather);
console.log(forecast);

.env:

REACT_APP_SECRET_KEY = "199023c4fb4dc2be4f6ae2b9d23f12bd";

您在应用程序中使用的引擎是什么。不同的引擎导入环境变量的方式不同。我认为,例如,对于vite,您必须在变量前面加上vite_关键字。我还想看看它是否会拾取你的变量。将其添加到handleOnSearchChange函数的顶部。

console.info("SECRET KEY", process.env.REACT_APP_SECRET_KEY);

编辑:我认为你的问题在于你对env变量的定义。去掉引号,看看它是否有效。

REACT_APP_SECRET_KEY=12345 // remove the quotes and spacing

现在,我不再获取{cod}:401,消息}:无效的API密钥。请参阅http://openweathermap.org/faq#error401了解更多信息"}

最新更新