简体   繁体   English

对多个 JS 文件中的 API 键使用 dotenv

[英]Using dotenv for API keys in multiple JS files

I am new to web programming but not programming in general.我是 web 编程的新手,但一般不会编程。 I use node.js to create a website and am using dotenv to hide API info form github and am having some trouble understanding something.我使用 node.js 创建网站,并使用 dotenv 隐藏 API 信息表格 github 并且在理解某些内容时遇到了一些麻烦。

My.env file is in the root directory and contains: My.env 文件位于根目录中,包含:

GOOGLE_CALENDAR_API_KEY=key_value

I use an app.js file to set up and run my server and send the index.html file.我使用 app.js 文件来设置和运行我的服务器并发送 index.html 文件。

//jshint esversion:6
const https = require('https');
const bodyParser = require("body-parser");
const express = require("express");
require("dotenv").config();

const app = express();

app.use(express.static("public"));

app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});

app.listen(5000, function(req, res) {
    console.log("Listening on port 5000.");
});

Then I have another script file I use named "custom.js" to run the bulk of my webapp.然后我有另一个名为“custom.js”的脚本文件来运行我的大部分 web 应用程序。 Inside, I try to use process.env to get the API key.在里面,我尝试使用 process.env 来获取 API 密钥。

window.onload = function()
{
  const googleAPIkey = process.env.GOOGLE_CALEDAR_API_KEY;
.
.
.

but I get an error "Uncaught ReferenceError: process is not defined"但我收到错误“未捕获的 ReferenceError:未定义进程”

I have also tried moving the require("dotenv").config() line to the custom.js file and that fails.我还尝试将 require("dotenv").config() 行移至 custom.js 文件,但失败了。 There is something I am doing wrong with trying to access information from one file into another, but I don't understand what.尝试将信息从一个文件访问到另一个文件时我做错了,但我不明白是什么。

Any help would be appreciated!任何帮助,将不胜感激!

From what's i understood you trying to access the process variable of node.js app from the client browser and it is not possible.据我了解,您试图从客户端浏览器访问 node.js 应用程序的过程变量,这是不可能的。 The process variable is only accessible in the scope of the node.js application and not in the browser where you run your client.流程变量只能在 node.js 应用程序的 scope 中访问,而不能在运行客户端的浏览器中访问。

you have to add require("dotenv").config();你必须添加require("dotenv").config(); on second script file also在第二个脚本文件上也

It looks like you are trying to access the Process variable on the client-side / frontend.看起来您正在尝试访问客户端/前端的 Process 变量。 You cannot access those variables from a client browser or machine您无法从客户端浏览器或机器访问这些变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM