0

I am using a .env file to store API Key. However, I can't seem to get to get my base JavaScript file to read the .env file. I have installed the dotenv npm package but it does not appear to be working and I am not sure what is going on.

I have made sure my .env is in the root of my project. See the picture below:

enter image description here

I have also installed the latest version of dotenv.

This is the code in the fixer-service.js that is trying to access the .env file:

require("dotenv").config();
const axios = require("axios");

const symbols = process.env.SYMBOLS || "EUR,USD,GBP";

const api = axios.create({
  baseURL: "http://data.fixer.io/api",
  params: {
    access_key: process.env.API_KEY
  },
  timeout: process.env.TIMEOUT || 5000
});

And this is the code in server.js that is trying to access the .env file:

require("dotenv").config();
const { getRates } = require("./lib/fixer-service");

// read .env files

const express = require("express");

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

And this is the code in the .env file (I have removed the API-Key):

API_KEY=api-key
PORT=3000
TIMEOUT=5000
SYMBOLS=EUR,USD,GBP,AUD,BTC,KES,JPY,CNY

When I tried to run my development server I get this error message:

(node:9045) UnhandledPromiseRejectionWarning: Error: missing_access_key
    at get (/Users/selina/Desktop/single-page-application/lib/fixer-service.js:22:9)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:9045) UnhandledPromiseRejectionWarning: Unhandled promise rejection.
    This error originated either by throwing inside of an async
    function without a catch block, or by rejecting a promise which was
    not handled with .catch(). (rejection id: 1)```
4

1 回答 1

0

我找到了一个解决方案,但没有很好的解释为什么它有效!如果有其他人参与解释,将不胜感激。

将参数从工作axios.create()转移api.get()

const api = axios.create({
  baseURL: 'http://data.fixer.io/api/',
  timeout: process.env.TIMEOUT || 5000
});

const get = async url => {
  const response = await api.get(url, {
    params: { access_key: process.env.API_KEY }
  });
  const { data } = response;
  if (data.success) {
    return data;
  }
  throw new Error(data.error.type);
};

于 2019-08-25T12:32:44.227 回答