LoginSignup
55
30

More than 5 years have passed since last update.

Cloud Functions for Firebase でCORSを許可する方法

Posted at

割とCORSを使用したいシチュエーションは多いのではないかと思い共有。
そもそものCloud Functionsの使い方が分からない方はこちらを参照してみてください。

expressのcorsパッケージを使うことによって実現します。

上記パッケージを npm install cors もしくは yarn add cors でインストールして、CORSを許可したい関数を以下のようにwrapします。

index.js
const functions = require('firebase-functions');
//importする際に {origin: true} をつける
//もう少し詳細に指定したい場合はこちらをご参照ください https://github.com/expressjs/cors#configuration-options
const cors = require('cors')({origin: true});

exports.withcors = functions.https.onRequest((request, response) => {
  //関数内全体をwrap
 cors(request, response, () => {
    response.status(200).send('success!');
  });
});

すごい短くなってしまいましたが、ご覧の通り簡単に実現できるので困ったらお試しください。

55
30
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
55
30