Webサイトから CloudFunctions の実行と躓いたところ
Webサイトから CloudFunctions の実行と躓いたところ:
firebaseオブジェクトを作っているなら、
CORSポリシー違反のエラー has been blocked by CORS policy
サーバ側にcorsの対応が必要
CloudFunctionsのプロジェクトで
メソッド実行部を
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 policyAccess 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.
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!" }));
}); // <= 追加
});
コメント
コメントを投稿