首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >.env文件和创建-反应-应用程序返回的问题

.env文件和创建-反应-应用程序返回的问题
EN

Stack Overflow用户
提问于 2020-08-05 12:11:16
回答 3查看 5.6K关注 0票数 0

我知道这个问题已经被问过无数次了,相信我,当我说我已经阅读过Stack溢出的页面,以及其他网站时,显然我已经浏览了文档。有些东西我一点也不理解,或者是我错过了一些愚蠢的东西。

我创建了一个React (使用npx创建-react)来使用API和fetch API创建一个小的天气信息服务(您认为这叫做?)。这都是前端(我还没有开始学习任何后端的东西)。

我的问题是我的.env文件。如前所述,我做了大量的研究,因此(希望)排除以下情况:

  1. 我的环境变量文本文件名为“..env”,位于我的根文件夹中(即与package.json文件和src &公用文件夹位于相同的位置)。

  1. 在.env文本文件中,变量的前缀为“REACT_APP_”.

我几乎肯定所有语法和变量名都是正确的,但这可能仍然是一个possibility?。

当我将API密钥直接放入我的fetch中时,所有操作都很完美,但在尝试从.env文件中获取API密钥时总是没有定义。我知道,因为我只是做前端,而且如果我将API推/上传到GitHub (或其他什么),它在技术上仍然是可见的,即使使用.gitignore也没有什么区别,但我仍然想要么修复它,要么找出为什么它不能为我自己的内心平静而工作。

据我所知,随着创建-反应-应用程序,没有其他模块/依赖(不确定正确的术语)需要安装通过终端,因为proccess.env都包括在这些天。据我所知,proccess.env应该用create来解决这个问题吗?

这是我的代码:

App.js

代码语言:javascript
复制
//Created by: Byron Georgopoulos
//Created on: 31/07/2020
//Last Updated on: 03/08/2020
//Description: Using Geolocation API, OpenWeatherMap API, and Fetch API, this React App displays the weather at the user current location,
//and a user can search the OpenWeatherMap database for the weather in (most) cities across the globe. 

//Import React
import React, { Component } from 'react';

//Import Fetch API
import 'isomorphic-fetch';

//Styling and React-Bootstrap
import './App.css';
import 'bootstrap/dist/css/bootstrap.min.css';
import Container from 'react-bootstrap/Container';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Form from 'react-bootstrap/Form';
import Button from 'react-bootstrap/Button';
import Card from 'react-bootstrap/Card';
import Modal from 'react-bootstrap/Modal';

//Get API key from .env file
const key = process.env.REACT_APP_WEATHER_API_KEY;
console.log('API Key: ', key);

class App extends Component {
  
  constructor(props) {
    
    super(props);
    
    this.state = {
      error: null,
      isLoaded: false,
      userCity: '',
      cityInfo: [],
      showModal: false,
    };

  }

  //Use Geolocation API to find users co-ordinants
  getPos = () => {
    return new Promise (function (resolve, reject){
      navigator.geolocation.getCurrentPosition(resolve, reject);
    });
  }

  //Get Latitude & Longitude, and search OpenWeatherMap API based on location (coords)
  getLocalWeather = async (latitude, longitude) => {
    const apiCall = await fetch(`http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${key}&units=metric`);
    const result = await apiCall.json();

    this.setState({ isLoaded: true });
    this.setState({ cityInfo: [result] });
  }

  //When Component Mounts
  componentDidMount() {

    this.getPos()
    .then((position) => {
      this.getLocalWeather(position.coords.latitude, position.coords.longitude)
    },
    (error) => {
      this.setState({
        isLoaded: true,
        error
      });
    })

  }

  //Handle user search
  handleCity = (event) => {
    let userCity = event.target.value;
    this.setState({ userCity: userCity });
  }

  //Search OpenWeatherMap API for user's city
  handleSubmit = () => {

    let userCity = this.state.userCity;
    this.refs.cityInput.value = '';

    fetch(`http://api.openweathermap.org/data/2.5/weather?q=${userCity}&appid=${key}&units=metric`)
        .then(res => res.json())
        .then(
          (result) => {
            this.setState({
              isLoaded: true,
              cityInfo: [result],
            });
          },
          (error) => {
            this.setState({
              isLoaded: true,
              error
            });
          }
        )
    
  }

  //Opens Help Modal
  openModal = () => 
  {
    this.setState({ showModal: true });
  }

  //Closes Help Modal
  closeModal = () => 
  {
    this.setState({ showModal: false });
  }

  render() {

    const error = this.state.error;
    const isLoaded = this.state.isLoaded;
    const cityInfo = this.state.cityInfo;

    if (error)
    {
      return <div>
                Error: {error.message}
              </div>;
    }
    else
    if (!isLoaded)
    {
      return <div className='LoadingMsg'>
                
                <br></br>
                <h2>Welcome to Open Weather Map API</h2>
                <hr></hr>
                <h5>Finding your location...</h5>
                <h6>Please 'Allow Location Access' in your browser to continue...</h6>
                <hr></hr>
                <br></br>

            </div>;
    }
    else
    {
      return (
        <div className='App'>
  
          <br></br>
          <h2>Open Weather Map API : Find the weather in your city.</h2>
          <hr></hr>
          <h6>This was created by Byron Georgopoulos for <a href='https://www.hyperiondev.com/' target='_blank'>HyperionDev</a> (L02T14) using
               React Components. It uses the <a href='https://openweathermap.org/api' target='_blank'>Open Weather Map API</a> and 
               the <a href='https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API' target='_blank'>Geolocation API</a> to first find 
               your current location and display the weather in your city (if access is allowed by the user), and a search bar to find the weather
              for over 200.000 cities worldwide thereafter.</h6>
          <hr></hr>
          <br></br>

          <Container>
            <Row>
              <Col sm={5}>
                <br></br>
                <br></br>
                <br></br>
                <br></br>
                <br></br>
                <Form id='cityForm'>
                  <Form.Group>
                    <Form.Label>Please Enter A City:</Form.Label>
                    <Form.Control onChange={this.handleCity} type='text' placeholder='e.g. Johannesburg' ref='cityInput' />
                    <br></br>
                    <Container>
                      <Row>
                        <Col>
                          <Button onClick={this.handleSubmit} variant='primary'>Search City</Button>
                        </Col>
                        <Col>
                          <Button onClick={this.openModal} id='helpBtn' variant='info'>Help / FAQ</Button>
                        </Col>
                      </Row>
                    </Container>
                  </Form.Group>
                </Form>
              </Col>
              <Col sm={7}>
                    {cityInfo.map(item => (
                      <Card id='weatherCard'>
                        <Card.Body>
                          <Card.Title><h3>Weather for <b>{item.name}</b>, {item.sys.country}.</h3></Card.Title>
                          <hr></hr>
                          <Card.Text><h5>It is currently: ±{Math.round(item.main.temp)}° C.</h5></Card.Text>
                          <Card.Text><h5>It feels like: ±{Math.round(item.main.feels_like)}° C.</h5></Card.Text>
                          <Card.Text><h5>The weather is: {item.weather[0].main}.</h5></Card.Text>
                          <Card.Text><h5>Sky Description: {item.weather[0].description}.</h5></Card.Text>
                          <Card.Text><h5>Humidity is at: {item.main.humidity}%.</h5></Card.Text>
                          <Card.Text><h5>Wind Speed is at: {item.wind.speed}m/s.</h5></Card.Text>
                        </Card.Body>
                      </Card>
                    ))}
              </Col>
            </Row>
          </Container>
          <br></br>
          <hr></hr>
          <br></br>
          
          <Modal id='helpModal' show={this.state.showModal} onHide={this.closeModal} animation={true} centered>
            <Modal.Body>
              <h4 id='modalHeading'>Help : Searching For A City</h4>
              <hr></hr>
              <Container>
                <Row>
                  <Col sm={1}>
                    <h6>1. </h6>
                  </Col>
                  <Col sm={11}>
                    <h6>You can only search cities in the input field. No countries, co-ordinates, provinces, states, etc.</h6>
                  </Col>
                </Row>
                <Row>
                  <Col sm={1}>
                    <h6>2. </h6>
                  </Col>
                  <Col sm={11}>
                    <h6>You can only search a cities FULL NAME. For example, LA ≠ Los Angeles, or JHB ≠ Johannesburg.</h6>
                  </Col>
                </Row>
                <Row>
                  <Col sm={1}>
                    <h6>3. </h6>
                  </Col>
                  <Col sm={11}>
                    <h6>That being said, searching for a city is NOT case sensitive. For example, los angeles = Los Angeles, or johannesburg = Johannesburg.</h6>
                  </Col>
                </Row>
                <Row>
                  <Col sm={1}>
                    <h6>4. </h6>
                  </Col>
                  <Col sm={11}>
                    <h6>± : Temperatures are rounded to the nearest whole number.</h6>
                  </Col>
                </Row>
                <Row>
                  <Col sm={1}>
                    <h6>5. </h6>
                  </Col>
                  <Col sm={11}>
                    <h6>Temperatures are in Degrees Celcius.</h6>
                  </Col>
                </Row>
              </Container>
            </Modal.Body>
            <Modal.Footer>
              <Button variant='danger' onClick={this.closeModal}>Close</Button>
            </Modal.Footer>
          </Modal> 

        </div>
      );
    }
  }
}

export default App;

package.json

代码语言:javascript
复制
    {
      "name": "weather-api",
      "version": "0.1.0",
      "private": true,
      "dependencies": {
        "@testing-library/jest-dom": "^4.2.4",
        "@testing-library/react": "^9.5.0",
        "@testing-library/user-event": "^7.2.1",
        "bootstrap": "^4.5.1",
        "es6-promise": "^4.2.8",
        "isomorphic-fetch": "^2.2.1",
        "react": "^16.13.1",
        "react-bootstrap": "^1.3.0",
        "react-dom": "^16.13.1",
        "react-scripts": "3.4.1"
      },
      "scripts": {
        "start": "react-scripts start",
        "build": "react-scripts build",
        "test": "react-scripts test",
        "eject": "react-scripts eject"
      },
      "eslintConfig": {
        "extends": "react-app"
      },
      "browserslist": {
        "production": [
          ">0.2%",
          "not dead",
          "not op_mini all"
        ],
        "development": [
          "last 1 chrome version",
          "last 1 firefox version",
          "last 1 safari version"
        ]
      }

}

.env (在=之前或之后没有空格,没有引号,X是我的API键)

代码语言:javascript
复制
REACT_APP_WEATHER_API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX

其他要注意的事项:

使用VS Code

  • React-Bootstrap的
  1. macOS Catalina 10.15.6 : Macbook 2017
  2. 是installed
  3. Using Firefox尝试运行该应用程序(通过我的终端中的“npm”)

很抱歉这么长时间,如果我漏掉了什么的话。对于所有这些仍然非常新,尤其是堆栈溢出。谢谢。

EN

回答 3

Stack Overflow用户

发布于 2020-08-05 12:13:51

您还应该安装该软件包:

代码语言:javascript
复制
npm i dotenv
票数 1
EN

Stack Overflow用户

发布于 2020-08-05 12:15:48

在构建时,read、read/creates env,所以每次修改.env文件时都需要npm run start,以便更新变量。

而且您不需要安装任何其他软件包,因为CRA (Create)已经随dotenv而来了。

只要您的密钥存在,就应该使用此{process.env. REACT_APP_WEATHER_API_KEY}

票数 0
EN

Stack Overflow用户

发布于 2020-08-05 12:19:53

Create中的

  1. 环境变量我们可以通过在本地JS文件中声明它们来将特定于环境的变量添加到我们的项目中。默认情况下,我们通过CRA为我们定义了NODE_ENV,并且可以添加以REACT_APP_.

开头的任何其他环境变量。

警告:不要将任何秘密(如私人API密钥)存储在您的React应用程序中!环境变量被嵌入到构建中,这意味着任何人都可以通过查看应用程序的文件来查看它们。

环境变量是在构建期间嵌入的。因为会生成一个静态的HTML/CSS/JS包,所以它不可能在运行时读取它们。

注意:您必须创建以REACT_APP_开头的自定义环境变量。除NODE_ENV之外的任何其他变量都将被忽略,以避免意外暴露可能具有相同名称的机器上的私钥。如果开发服务器正在运行,更改任何环境变量都需要重新启动它。

  1. 管理.env文件中的环境变量我们可以创建一个名为.env的文件,我们可以在其中存储环境变量。此.env文件将被视为定义永久环境变量的默认文件。

现在,我们需要创建其他.env文件,以支持暂存和生产环境。因此,让我们创建.env.staging和.env.production文件。

所以这些文件看起来像,

代码语言:javascript
复制
// **.env**

REACT\_APP\_TITLE = "My Awesome App"
REACT\_APP\_SESSION\_TIME = "60"

// **.env.staging**

REACT\_APP\_API\_BASE\_URL = "https://app.staging.com/api/"

// **.env.production**

REACT\_APP\_API\_BASE\_URL = "https://app.prod.com/api/"

  1. 安装env-cmd包,现在我们已经准备好了单独的env文件,我们可以使用它们进行特定于环境的构建。我们将使用npm包*env-cmd *.

环境-cmd

这是一个简单的节点程序,用于使用env文件中的环境执行命令。使用以下命令安装此软件包,

代码语言:javascript
复制
**npm install env-cmd**

  1. 创建命令以创建特定于环境的构建,现在打开package.json文件并添加以下脚本,

“脚本”:{“开始”:“反应-脚本启动”,“启动:阶段”:"env-cmd -f .env.staging react- .env.staging -script start", "start:prod":"env-cmd -f .env.production react scripts start", "build":“prod script build",”build:start“:"env-cmd -f .env.staging react构建”, "build:prod":"env-cmd -f .env.production react -test“:”test script test"," eject“:”test-f eject“}

https://dev.to/rishikeshvedpathak/react-environment-specific-builds-using-env-with-cra-and-env-cmd-296b

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63264920

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档