简体   繁体   中英

My env variable works on localhost but is undefined when deployed on Netlify

Having trouble getting an axios GET request to work on Netlify because the env variable that defines my api key comes up as undefined on Netlify. I have already set the env variable with 'Site settings > Build & deploy > Environment > Environment variables'. But when I try it on Netlify I get:

GET https://api.openweathermap.org/data/2.5/forecast?q=London&appid=undefined&units=imperial
error forecast: AxiosError: Request failed with status code 401

Here is my code that makes the GET request:

import { Forecast } from './forecast';
import axios from 'axios';

export class DOM {
    static displayFiveDayForecast = (city) => {
        const BASE_URL_FIVE_DAY_FORECAST = 'https://api.openweathermap.org/data/2.5/forecast';

        axios.get(`${BASE_URL_FIVE_DAY_FORECAST}?q=${city}&appid=${process.env.API_KEY}&units=imperial`)
        .then(res => {
            const weatherObj = Forecast.createForecasts(res.data);
            const content = document.getElementById('content');

            const forecastDiv = document.createElement('div');
            forecastDiv.id = 'forecast';
            content.appendChild(forecastDiv);

            for(let value in weatherObj.forecasts) {
                const forecastBox = document.createElement('div');
                forecastBox.className = 'forecast-item';
                forecastDiv.appendChild(forecastBox);

                const date = document.createElement('div');
                date.textContent = weatherObj.forecasts[value][0];
                forecastBox.appendChild(date);

                const icon = document.createElement('img');
                icon.src = weatherObj.forecasts[value][3];
                icon.alt = 'forecast icon';
                forecastBox.appendChild(icon);

                const main = document.createElement('div');
                main.textContent = `${weatherObj.forecasts[value][1]} F\u00B0`;
                forecastBox.appendChild(main);

                const feelsLike = document.createElement('div');
                feelsLike.textContent = `Feels like ${weatherObj.forecasts[value][2]} F\u00B0`;
                forecastBox.appendChild(feelsLike);
            }
        })
        .catch(err => {console.log(`error forecast: ${err}`)})
    }
}

This GET request works fine on localhost and the api key is defined there. I'm using webpack if that information helps.

package.json:

{
  "name": "javascript-weather-app",
  "version": "1.0.0",
  "description": "A weather application using the openweather api",
  "main": "index.js",
  "scripts": {
    "start": "webpack-dev-server --config webpack.dev.js --open",
    "build": "webpack --config webpack.prod.js"
  },
  "author": "tgoandrex",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.27.2",
    "css-loader": "^6.7.1",
    "dotenv": "^16.0.1",
    "html-webpack-plugin": "^5.5.0",
    "style-loader": "^3.3.1",
    "webpack": "^5.73.0",
    "webpack-cli": "^4.10.0",
    "webpack-dev-server": "^4.9.2",
    "webpack-merge": "^5.8.0"
  }
}

webpack.common.js:

const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
require('dotenv').config({ path: './.env' });


module.exports = {
    entry: './src/index.js',
    plugins : [
        new HtmlWebpackPlugin({
            template: './src/template.html'
        }),
        new webpack.DefinePlugin({
            'process.env': JSON.stringify(process.env)
        })
    ],
    module: {
        rules: [
            {
                test: /\.css$/,
                use: ['style-loader', 'css-loader']
            }
        ]
    }
}

If you define gatsby environment .env file then it only accealbe on the gatsby config file. But if you need to access across sites then you must need to define the prefix GATSBY_

Ex. GATSBY_BASE_URL_FIVE_DAY_FORECAST

So I found out all I had to do was define a variable in my function and set it as the environment variable. I still don't understand why this works and just taking process.env.API_KEY directly doesn't.

const apiKey = process.env.API_KEY;
axios.get(`${BASE_URL_FIVE_DAY_FORECAST}?q=${city}&appid=${apiKey}&units=imperial`)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM