drn1008
2019-07-24 13:33
浏览 156
已采纳

如何在AWS EC2中为React&Go设置环境变量

I've made React & Go product in local. And I'm going to deploy it to AWS EC2.

To work in AWS EC2, I need to set environment variables for some secret information.

I've already set env variables for local environment. But I'm not sure about env variables working for production environment(AWS EC2).

I already set env. file for local environment. But not sure how to set environment variables in ec2.

I use environment variables for axios, firebase and mysql.

//axios
   const client = axios.create({
      baseURL: process.env.REACT_APP_API_URL,
    });
    client
      .get('/api/articles')
      .then(response => {
        this.setState({articles: response.data});
      })
      .catch(response => console.log('ERROR!! occurred in Backend.'));
//firebases
const firebaseConfig = {
  apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
  authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
  databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
  projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
  storageBucket: '',
  messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.REACT_APP_FIREBASE_APP_ID,
};

firebase.initializeApp(firebaseConfig);

export default firebase;
//mysql
    err := godotenv.Load()
    if err != nil {
        //TODO production

    }
    db, err := sql.Open("mysql", os.Getenv("MYSQL_USER")+":"+os.Getenv("MYSQL_PASSWORD")+"@tcp(localhost:3306)/article")
    if err != nil {
        panic(err.Error())
    }

    defer db.Close()

    err = db.Ping()
    if err != nil {
        panic(err.Error())
    }

Here is the github. https://github.com/jpskgc/article

I'm going to deploy this React & Golang product in AWS EC2. But I'm not sure how to set environment variables.

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dortmundbvb0624 2019-08-21 08:17
    已采纳

    I use elastic beanstalk and set environment variables there.

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongshendi3599 2019-07-24 15:44

    In the shell script you are using to launch your server on EC2, add the environment variable definition, for example :

    export ENV_VAR_1=value_1
    export ENV_VAR_2=value_2
    
    ... start your server ...
    

    Note that this will only work for the server side. The React App is made of Javascript running in the client's browser and you can not control the environment variables there.

    If I understand well, the Axios code extract above is part of the React front end. You can not have process.env there as this is executed on customer machine.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题