首页 > 解决方案 > Browserify 后 Dotenv 未定义

问题描述

当我使用 API 密钥以字符串格式运行代码时,此代码有效,但我想使用.env变量。我已经安装,在同一目录中npm install dotenv创建了一个.env文件。我知道要在脚本中尽早使用.env 。require("dotenv").config()

由于你不能在浏览器中使用require,所以我已经安装了npm install -g browserify.

当我browserify main.js -o bundle.js在 Index 中运行和更改 javaScript 源时,此代码仍然有效。

当我取消注释//require("dotenv").config()并使用const apiTest = process.env.API_KEY身份验证时,问题就出现了。

错误:

    Uncaught (in promise) TypeError: data is undefined
    updateScreen http://127.0.0.1:8080/bundle.js:765
    promise callback*updateScreen http://127.0.0.1:8080/bundle.js:764
    [4]</</</< http://127.0.0.1:8080/bundle.js:783
    EventListener.handleEvent*[4]</</< http://127.0.0.1:8080/bundle.js:781
    [4]</< http://127.0.0.1:8080/bundle.js:786
    [4]< http://127.0.0.1:8080/bundle.js:786
    o http://127.0.0.1:8080/bundle.js:1
    r http://127.0.0.1:8080/bundle.js:1
    <anonymous> http://127.0.0.1:8080/bundle.js:1
bundle.js:765:25

捆绑.js:765:25:

function updateScreen() {
  //data is a random word, but it represents the return of  getSuggestions()
  getSuggestions().then((data) => {
    const arrayLengde = data.quotes.length;
    if (1 >= arrayLengde) {
      let poem = data.quotes[0].body;
      let poemAuthor = data.quotes[0].author;
      document.getElementById("author").innerHTML = poemAuthor;
      document.getElementById("responseField").innerHTML = poem;
    } else if (1 <= arrayLengde) {
      const randomIndex = Math.floor(Math.random() * arrayLengde);
      poem = data.quotes[randomIndex].body;
      poemAuthor = data.quotes[randomIndex].author;
      document.getElementById("author").innerHTML = poemAuthor;
      document.getElementById("responseField").innerHTML = poem;
    }
  });
}

之所以定义它,是因为如果我不使用.env ,它就可以工作。在检查了 Get request HEADER 后,我发现这是我发现的:

Status 401

Authorization: Token token=undefined

主.js:

//DOTENV with help from Browserify
//require("dotenv").config()


//info om API
const apiTest = process.env.API_KEY
const apiKey = 'NUMBERS_HERE'
const url = "https://favqs.com/api/";
const queryparam1 = "quotes/?filter=";
const queryparam2 = "&type=tag";

//selecting page element
const inputField = document.querySelector("#input");
const form = document.getElementById("form");

//ajax function
async function getSuggestions() {
  const wordQuery = inputField.value;
  const filterQueryParam = `${queryparam1}${wordQuery}${queryparam2}`;
  const endpoint = `${url}${filterQueryParam}`;
  try {
    const response = await fetch(endpoint, {
      method: "GET",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Token token=${apiKey}`,
      },
    });
    if (response.ok) {
      const data = response.json();

      return data;
    }
  } catch (error) {
    console.log(error);
  }
}

function updateScreen() {
  //data is a random word, but it represents the return of  getSuggestions()
  getSuggestions().then((data) => {
    const arrayLengde = data.quotes.length;
    if (1 >= arrayLengde) {
      let poem = data.quotes[0].body;
      let poemAuthor = data.quotes[0].author;
      document.getElementById("author").innerHTML = poemAuthor;
      document.getElementById("responseField").innerHTML = poem;
    } else if (1 <= arrayLengde) {
      const randomIndex = Math.floor(Math.random() * arrayLengde);
      poem = data.quotes[randomIndex].body;
      poemAuthor = data.quotes[randomIndex].author;
      document.getElementById("author").innerHTML = poemAuthor;
      document.getElementById("responseField").innerHTML = poem;
    }
  });
}

form.addEventListener("submit", (e) => {
  e.preventDefault();
  updateScreen();
});

标签: javascriptenvironment-variablesbrowserify

解决方案


添加 .catch((err) => {}) 第 v


推荐阅读