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

Webサイトから 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 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!" })); 
  }); // <= 追加 
}); 

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2020-12-01 09:41:49 RSSフィード2020-12-01 09:00 分まとめ(69件)