ChatGPTとGitHub Copilotを活用しながらWebアプリケーションを作る【APIのURLを環境変数で設定する】

以下の記事の続きです。

programming-gogogogo.hatenablog.com

上記の記事の段階では、APIのエンドポイントをハードコーディングしているので、この記事では環境変数を使うように変更したい思います。

Vue.jsで環境変数を定義する方法について、ChatGPTに質問しました。

入力

How can I use environmental variables in Vue CLI application?

出力

You can use environmental variables in a Vue CLI application by defining them in a .env file or using the appropriate command line arguments when you start the development server or build your application.

Here are the steps to follow:

Create a .env file in the root directory of your Vue CLI application.

Define your environmental variables in the .env file using the format VARIABLE_NAME=value. For example:

VUE_APP_API_KEY=abc123
VUE_APP_BASE_URL=http://localhost:3000

Note that the prefix VUE_APP_ is required for all environmental variables that you want to use in your Vue application.

Restart your development server for the environmental variables to take effect.

To access an environmental variable in your Vue application, you can use the process.env object. For example, to access the VUE_APP_API_KEY environmental variable defined above, you can use:

const apiKey = process.env.VUE_APP_API_KEY;

You can use this variable in your code just like any other variable.

When building your application for production, you can define the environmental variables using the --env flag. For example:

vue-cli-service build --mode production --env VUE_APP_API_KEY=abc123 VUE_APP_BASE_URL=http://localhost:3000

This will build your application with the specified environmental variables. Note that you can also define environmental variables in a .env.production file to be used during production builds.

Vue.jsで環境変数を使うには、.envファイルで VUE_APP_というprefixをつけて定義する必要があるようです。 上記を参考に.envファイルを作成してみます。

ls
README.md               package.json
babel.config.js         public
jsconfig.json           src
node_modules            vue.config.js
package-lock.json

touch .env

.envを以下のように編集します。

VUE_APP_API_URL=http://localhost:8000/api/

vueファイルのdata()内でapiUrl変数を定義するように修正しました。

<script>
export default {
  data() {
    return {
      apiUrl: process.env.VUE_APP_API_URL + 'users/',
      users: [],
      name: '',
      email: ''
    }
  },
  mounted() {
    fetch(this.apiUrl)
      .then(response => response.json())
      .then(data => {
        this.users = data;
      })
      .catch(error => console.error(error));
  },
  methods: {
    createUser() {

    fetch(this.apiUrl, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            name: this.name,
            email: this.email
          })
        })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error(error));
  }
  }
}
</script>

再度npm run serveでローカルサーバーを起動して、アプリケーションが正常に動作することを確認できました。

これで本番環境にデプロイする際にも、APIのエンドポイントを指定する環境変数の値を変更することで対応しやすくなると思います。

ここまでの状態をGitHubにpushしました。

github.com