可以从.env-file访问api-key

发布于 2025-02-05 12:34:44 字数 1769 浏览 4 评论 0原文

尝试在我们的server.js中获取时,我们会从.env文件访问API-KEY时遇到问题。如果我们将API-KEY手动添加到Server.js中的URL中,则该问题似乎是Server.js和.env-File之间的连接。 我们已安装了NPM DOTENV。 在.env文件中,我们已经编写了这样的密钥:weather_api_key = xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx的的

内容的内容?

import express from "express";
import cors from "cors";
import mongoose from "mongoose";
import crypto from "crypto";
import bcrypt from "bcrypt";
import request from "request";
import dotenv from "dotenv";
// import { stringify } from "querystring";

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.Promise = Promise;

const port = process.env.PORT || 8080;
const app = express();

dotenv.config();


app.get("/home", (req, res) => {
  let city = req.query.city;
  // const request = require("request");
  // const options = {
  //   url: `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.WEATHER_API_KEY}`,
  //   method: "GET",
  //   headers: {
  //     Accept: "application/json",
  //   },
  // };
  const key = "*******************";
  const requesturl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${key}`;
  request(requesturl, function (error, response, body) {
    let data = JSON.parse(body);
    console.log(response);
    if (response.statusCode === 200) {
      res.send(`The weather in ${city} is ${data.weather[0].description}`);
    } else {
      res.send(data.message);
    }
  });
  console.log(process.env.WEATHER_API_KEY);
});

We are having problem accessing the API-key from our .env file when trying to fetch in our server.js. If we add the API-key manually to the URL in server.js it works, so the problem seems to be the connection between server.js and .env-file.
We have npm installed dotenv.
In the .env file we have written the key like this: WEATHER_API_KEY = XXXXXXXXXXXX

Does anyone know what we have done wrong?

import express from "express";
import cors from "cors";
import mongoose from "mongoose";
import crypto from "crypto";
import bcrypt from "bcrypt";
import request from "request";
import dotenv from "dotenv";
// import { stringify } from "querystring";

const mongoUrl = process.env.MONGO_URL || "mongodb://localhost/project-mongo";
mongoose.connect(mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true });
mongoose.Promise = Promise;

const port = process.env.PORT || 8080;
const app = express();

dotenv.config();


app.get("/home", (req, res) => {
  let city = req.query.city;
  // const request = require("request");
  // const options = {
  //   url: `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.WEATHER_API_KEY}`,
  //   method: "GET",
  //   headers: {
  //     Accept: "application/json",
  //   },
  // };
  const key = "*******************";
  const requesturl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${key}`;
  request(requesturl, function (error, response, body) {
    let data = JSON.parse(body);
    console.log(response);
    if (response.statusCode === 200) {
      res.send(`The weather in ${city} is ${data.weather[0].description}`);
    } else {
      res.send(data.message);
    }
  });
  console.log(process.env.WEATHER_API_KEY);
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

狠疯拽 2025-02-12 12:34:44

您可以尝试

import 'dotenv/config';

从“ dotenv”; 导入,然后删除dotenv.config();呼叫。

来源和说明: https://github.com/ motdotla/dotenv#how-do-i-i--i--i---with-import

并更新请求URL(您可能是为了测试目的而更改的)

const requesturl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.key}`;

,以便尝试在没有任何空间的情况下定义密钥不太可能是根本原因。

WEATHER_API_KEY="XXXXXXXXXXXX"

You may try this

import 'dotenv/config';

in place of import dotenv from "dotenv"; and remove the dotenv.config(); call.

Source and explanation: https://github.com/motdotla/dotenv#how-do-i-use-dotenv-with-import

And update the request URL (which you might have changed for testing purpose) to

const requesturl = `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${process.env.key}`;

Also, try defining your key without any spaces, though this is less likely to be the root cause.

WEATHER_API_KEY="XXXXXXXXXXXX"
微凉徒眸意 2025-02-12 12:34:44

尽管问题不是针对反应的,但对于使用React的人可能会有所帮助。对于React应用程序,环境变量必须从React_App_前缀开始,否则它将无法使用。

react_app_weather_api_key =“ xxxxxxxxxxxx”

Although the question is not specifically about React, it might be helpful for those who use React. For a React App, Environment Variables have to start with the REACT_APP_ prefix otherwise it won't work.

REACT_APP_WEATHER_API_KEY="XXXXXXXXXXXX"

初熏 2025-02-12 12:34:44

如果您的.env文件是这样的:

OPENAI_API_KEY = "YOUR_CUSTOM_KEY"

import load_dotenvfind_dotenv

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

测试是否有效:

import os
import openai
from dotenv import load_dotenv, find_dotenv

_ = load_dotenv(find_dotenv())

openai.api_key = os.getenv("OPENAI_API_KEY")

print(openai.api_key)

If your .env file is something like this:

OPENAI_API_KEY = "YOUR_CUSTOM_KEY"

Import load_dotenv and find_dotenv

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())

Test if it works:

import os
import openai
from dotenv import load_dotenv, find_dotenv

_ = load_dotenv(find_dotenv())

openai.api_key = os.getenv("OPENAI_API_KEY")

print(openai.api_key)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文