Skip to content
Advertisement

Can’t access API-key from .env-file

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

Advertisement

Answer

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"
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement