4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Webサイトから CloudFunctions の実行と躓いたところ

Last updated at Posted at 2019-01-25

Webサイトからcallメソッドで呼び出し

firebaseオブジェクトを作っているなら、functionsを作成しておくとリクエストが簡単になる。

var myFunctions = firebase.functions();
myFunctions.call("helloWorld"); // 叩くだけの場合
myFunctions.call("helloWorld").then((data) => { // 結果を使用する場合
  console.log(data);
});

firebase serve を使用する場合は、以下の修正でテストサーバを参照可能

var myFunctions = firebase.functions();
myFunctions.emulatorOrigin = "http://localhost:5000"; // <= 追加
myFunctions.call("helloWorld");

CORSのエラー

CORSポリシー違反のエラー has been blocked by CORS policy

Access to fetch at 'https://example.cloudfunctions.net/helloWorld' from origin 'http://localhost' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

サーバ側にcorsの対応が必要
CloudFunctionsのプロジェクトで npm install -S cors を実行する。
メソッド実行部を cors() で囲むように修正。

const functions = require('firebase-functions');
const cors = require("cors")({ origin: true }); // <= 追加

exports.helloWorld = functions.https.onRequest((request, response) => {
  cors(request, response, () => { // <= 追加
    response.send(JSON.stringify({ data: "Hello from Firebase!" }));
  }); // <= 追加
});
4
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
4
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?