Я хочу использовать dotenv, чтобы скрыть свой ключ API.
когда я удаляю require('dotenv').config(); из моего кода и поместил свой ключ API в apiKey:process.env.API_KEY, вместо процесса.env.API_KEY, код работает.
Я установил dotenv, а также проверил свои зависимости< /p>
Я создал папку .env и упомянул API_KEY=2947****
Я создал файл .gitignore и поместил в него .env р>
но когда я попытался использовать его в своем файле script.js, он не работал
require('dotenv').config();
let weather = {
apiKey: process.env.API_KEY,
fetchWeather: function (city) {
fetch(
"https://api.openweathermap.org/data/2.5/weather?q=" +
city +
"&units=metric&appid=" +
this.apiKey
)
.then((response) => {
if (!response.ok) {
alert("No weather found.");
throw new Error("No weather found.");
}
return response.json();
})
.then((data) => this.displayWeather(data));
},
displayWeather: function (data) {
const { name } = data;
const { icon, description } = data.weather[0];
const { temp, humidity,temp_min,temp_max } = data.main;
const { speed } = data.wind;
// const { sunrise, sunset } = data.sys;
document.querySelector(".city").innerText = "Weather in " + name;
document.querySelector(".icon").src ="https://openweathermap.org/img/wn/" + icon + ".png";
document.querySelector(".description").innerText = description;
document.querySelector(".temp").innerText = temp + " °C";
document.querySelector(".humidity").innerText ="Humidity: " + humidity + "%";
document.querySelector(".wind").innerText ="Wind speed: " + speed + " km/h";
document.querySelector(".min").innerText ="Min Temp: " + temp_min + " °C";
document.querySelector(".max").innerText ="Max Temp: " + temp_max + " °C";
// document.querySelector(".sunrise").innerText =
// "Sunrise: " + sunrise + " °C";
// document.querySelector(".sunset").innerText =
// "Sunset: " + sunset + " °C";
document.querySelector(".weather").classList.remove("loading");
// document.body.style.backgroundImage =
// "url('https://source.unsplash.com/1600x900/?" + name + "')";
},
search: function () {
this.fetchWeather(document.querySelector(".search-bar").value);
},
};
document.querySelector(".search button").addEventListener("click", function () {
weather.search();
});
document
.querySelector(".search-bar")
.addEventListener("keyup", function (event) {
if (event.key == "Enter") {
weather.search();
}
});
weather.fetchWeather("Pune");
Подробнее здесь: https://stackoverflow.com/questions/747 ... ing-dotenv
Как скрыть свой ключ API в файле script.js с помощью dotenv ⇐ Html
Программисты Html
-
Anonymous
1736104322
Anonymous
Я хочу использовать dotenv, чтобы скрыть свой ключ API.
когда я удаляю require('dotenv').config(); из моего кода и поместил свой ключ API в apiKey:process.env.API_KEY, вместо процесса.env.API_KEY, код работает.
Я установил dotenv, а также проверил свои зависимости< /p>
Я создал папку .env и упомянул API_KEY=2947****
Я создал файл .gitignore и поместил в него .env р>
но когда я попытался использовать его в своем файле script.js, он не работал
require('dotenv').config();
let weather = {
apiKey: process.env.API_KEY,
fetchWeather: function (city) {
fetch(
"https://api.openweathermap.org/data/2.5/weather?q=" +
city +
"&units=metric&appid=" +
this.apiKey
)
.then((response) => {
if (!response.ok) {
alert("No weather found.");
throw new Error("No weather found.");
}
return response.json();
})
.then((data) => this.displayWeather(data));
},
displayWeather: function (data) {
const { name } = data;
const { icon, description } = data.weather[0];
const { temp, humidity,temp_min,temp_max } = data.main;
const { speed } = data.wind;
// const { sunrise, sunset } = data.sys;
document.querySelector(".city").innerText = "Weather in " + name;
document.querySelector(".icon").src ="https://openweathermap.org/img/wn/" + icon + ".png";
document.querySelector(".description").innerText = description;
document.querySelector(".temp").innerText = temp + " °C";
document.querySelector(".humidity").innerText ="Humidity: " + humidity + "%";
document.querySelector(".wind").innerText ="Wind speed: " + speed + " km/h";
document.querySelector(".min").innerText ="Min Temp: " + temp_min + " °C";
document.querySelector(".max").innerText ="Max Temp: " + temp_max + " °C";
// document.querySelector(".sunrise").innerText =
// "Sunrise: " + sunrise + " °C";
// document.querySelector(".sunset").innerText =
// "Sunset: " + sunset + " °C";
document.querySelector(".weather").classList.remove("loading");
// document.body.style.backgroundImage =
// "url('https://source.unsplash.com/1600x900/?" + name + "')";
},
search: function () {
this.fetchWeather(document.querySelector(".search-bar").value);
},
};
document.querySelector(".search button").addEventListener("click", function () {
weather.search();
});
document
.querySelector(".search-bar")
.addEventListener("keyup", function (event) {
if (event.key == "Enter") {
weather.search();
}
});
weather.fetchWeather("Pune");
Подробнее здесь: [url]https://stackoverflow.com/questions/74729632/how-do-i-hide-my-api-key-in-script-js-file-using-dotenv[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия