[英]Trouble using env variables
在簡化使用 Github API 過濾用戶和存儲庫的過程后,我最近了解到擁有與 API 相關的信息,如 API 密鑰、ID 等是不好的做法。 在我的特殊情況下,有 client_ID 和 client_secret。 我最近了解了環境變量以及如何將它們與 dotenv 包一起使用,但我正在努力學習如何使用它。 這是我嘗試過的:
我曾嘗試制作一個 server.js 文件,在將環境變量放入 env 文件后,我將在其中存儲環境變量。 我在這方面成功了,但我不能在 github.js 文件中使用它們
我嘗試在我的github.js文件中直接使用requires dotenv包,但是彈出一個錯誤,說我的類 (Github) 未定義。
我嘗試將 env 變量從server.js文件導入和導出到github.js文件,但無法訪問我的 Github 類。
我是不是遺漏了什么,還是我使用的這些環境變量都錯了?
相關代碼如下
github.js
class Github {
constructor() {
this.client_ID = "1037a4472aafe; // Trying to hide this
this.client_secret = "aaad41dd6b1cf2331"; // Trying to hide this
this.repos_count = 5;
this.repos_sort = "created: asc";
}
async getUser(user) {
const profileResponse = await fetch(`https://api.github.com/users/${user}?client_id=${this.client_ID}&client_secret=${this.client_secret}`);
const repoResponse = await fetch(`https://api.github.com/users/${user}/repos?per_page=${this.repos_count}&sort=${this.repos_sort}&client_id=${this.client_ID}&client_secret=${this.client_secret}`);
const profileData = await profileResponse.json();
const repoData = await repoResponse.json();
return {
profileData: profileData,
repoData: repoData
}
}
}
應用程序.js
// Instantiate GITHUB class
const github = new Github;
// Instantiate UI class;
const ui = new UI;
// Search input
const searchUser = document.getElementById("searchUser");
//search input event listner
searchUser.addEventListener("keyup", (e) => {
// Get input text
const userText = e.target.value;
if (userText !== "") {
// Make HTTP call
github.getUser(userText)
.then((data) => {
if (data.profileData.message === "Not Found") {
//show alert
ui.showAlert("User not found", "alert alert-danger");
}
else {
// Show the profile
ui.showProfile(data.profileData);
ui.showRepos(data.repoData);
ui.logInfo(data.profileData);
}
});
}
else {
// Clear the profile
ui.clearProfile();
}
});
.env
client_ID=1037a4472aafe
client_secret=aaad41dd6b1cf2331
服務器.js
const express = require("express");
const path = require("path");
const port = process.env.PORT || 8080;
const app = express();
require("dotenv").config();
const client_ID = process.env.client_ID;
const client_secret = process.env.client_secret;
app.use(express.json());
app.use(express.static(path.join(__dirname, "src")));
app.get("*", (request, response) => {
response.sendFile(path.resolve(__dirname, "src/index.html"))
});
console.log(process.env)
app.listen(port, () => {
console.log(`Server running on port ${port}`);
});
你在使用某種bundler
嗎? ,如果是這種情況,您應該開始研究如何在bundler
使用env
變量。
例如:如果您使用webpack
,則必須在webpack.config
上配置變量。
這篇文章與您的問題有關,但與 webpack
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.