LoginSignup
6
3

More than 3 years have passed since last update.

Firebase Hosting上でCloud Functionsを使うときに気をつけること【CORS】

Last updated at Posted at 2019-10-18

Firebaseとても便利ですね。
HostingやCloud Functionsによる関数の実行など、アプリケーションを作成する上で、様々なことを助けてくれます。

NuxtjsをFirebase Hosting上で動かして、APIからデータを取得するアプリを作る際に、
Cloud Functionsを利用しました。

その際に、CORSの問題でかなり時間を使ってしまったため、記事にします。

こちらの記事を参考にさせてもらいました。
ありがとうございました。

前提

  • Firebase Hosting上で動作しているアプリケーション。
  • Cloud Functionsをaxiosを用いて実行する。

Cloud Functionのコード

まずは、Cloud Functionのコードを書きます。

index.js
const functions = require('firebase-functions')

exports.helloWorld = functions.https.onRequest(async (request, response) => {
  await response.send('hello world!')
})

こちらのコマンドでデプロイが可能です。

$ firebase deploy --only functions

firebase.jsonの設定

次に、Firebase Hostingのrewriteの設定を追加します。

この部分がわからず、CORSのエラーがでて、ずっとつまづいてしまいました。。。

firebase.json
"hosting": {
    "public": "dist", // nuxtのデフォルトの静的ファイル出力先
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ],
    "rewrites": [
      {
        "source": "/getMessage",
        "function": "helloWorld" // 先ほど作成した関数名を指定します
      },
      {
        "source": "**",
        "destination": "/index.html"
      }
    ]
  }

アプリケーションから関数を呼び出す

最後にアプリケーション側から関数を呼び出します。

今回は、Nuxtjsを使っているため、.vueファイルで記述しています。

sample.vue
<template>
  <div>
    {{ message }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: ''
    }
  },
  created() {
    this.getMessage()
  },
  methods: {
    async getMessage() {
      try {
        // nuxtのaxiosモジュールを使用
        this.message = await this.$axios.$get('/getMessage')
      } catch (err) {
        console.log(err)
      }
    }
  }
}
</script>

以下のコマンドでデプロイします。

$ yarn generate // Nuxtの静的ファイルの生成コマンド
$ firebase deploy --only hosting

messageにHelloWorldが表示されれば、完了です。

【おまけ】ローカル開発時

ちなみにローカル開発時には

$ firebase serve

コマンドがとても便利です。(yarn run devコマンドを使って進めると、firebase.jsonが反映されなくて困ります。)

Hostingのデプロイするfirebase.jsonで指定したpublicフォルダに対してホスティングされるため、
Nuxtjsで利用する際には、

$ yarn generate

コマンドをお忘れなく!

最後まで読んでいただき、ありがとうございました!

6
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
3