繁体   English   中英

我的 env 变量在 localhost 上工作,但在 Netlify 上部署时未定义

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

无法使 axios GET 请求在 Netlify 上工作,因为定义我的 api 密钥的环境变量在 Netlify 上未定义。 我已经使用“站点设置 > 构建和部署 > 环境 > 环境变量”设置了 env 变量。 但是当我在 Netlify 上尝试时,我得到:

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

这是我发出 GET 请求的代码:

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

此 GET 请求在 localhost 上运行良好,并且 api 密钥在此处定义。 如果该信息有帮助,我正在使用 webpack。

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']
            }
        ]
    }
}

如果您定义了 gatsby 环境 .env 文件,那么它只适用于 gatsby 配置文件。 但是如果你需要跨站点访问那么你必须定义前缀GATSBY_

前任。 GATSBY_BASE_URL_FIVE_DAY_FORECAST

所以我发现我所要做的就是在我的函数中定义一个变量并将其设置为环境变量。 我仍然不明白为什么这行得通,而直接采用process.env.API_KEY则不行。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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