Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - Dotenv undefined after Browserify

When I run my code with the API key in a string format this code works, but i wanna use the .env variables. I have installed npm install dotenv, made a .env file in the same directory. I know that to use the .env you need to require("dotenv").config() as early as possible in the script.

Since you can't use the require in the browser, I have installed npm install -g browserify .

When i run browserify main.js -o bundle.js and change javaScript source in Index, this code still works.

When I uncomment the //require("dotenv").config() and use the const apiTest = process.env.API_KEY for the authentication that's where the problem comes.

Error:

    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

Bundle.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;
    }
  });
}

It is defined because it works if i don't use the .env. After inspecting the Get request HEADER i get back this is what i find:

Status 401

Authorization: Token token=undefined

Main.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();
});
question from:https://stackoverflow.com/questions/66056100/dotenv-undefined-after-browserify

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...