从 firebase 网络应用调用云函数

Calling a cloud function from a firebase web app

我正在尝试在 firebase 网络应用程序中使用云功能,但遇到了一些问题。如果有人可以指出一些设置或其他我可能遗漏的东西,那将会很有帮助。

首先是云函数的相关代码:

exports.myFunc = functions.https.onRequest(function(req, resp) {
  const from = req.body.sender;
  admin.auth().getUserByEmail(from)
      .then(function(userRecord) {
       console.log("Successfully fetched user data:", userRecord.toJSON());
      })
      .catch(function(error) {
        console.log("Error fetching user data:", error);
      });
});

第二个是网络应用中调用云函数的代码:

var xhr = new XMLHttpRequest();
xhr.open("POST", "https://us-central1-myapp.cloudfunctions.net/myFunc", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(JSON.stringify({
    from: "example@example.com"
}));
xhr.onload = function() {
    var data = JSON.parse(this.responseText);
    console.log('THE DATA:',data);
};

最后,这是我在按下按钮触发呼叫后在 Web 控制台中看到的消息:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-myapp.cloudfunctions.net/myFunc. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing). Status code: 408.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://us-central1-myapp.cloudfunctions.net/myFunc. (Reason: CORS request did not succeed). Status code: (null).

此时服务器日志中没有任何相关内容。

您需要安装 cors 并像这样使用它,

import * as cors from "cors"; 
const corsHandler = cors({ origin: true });
 
// allow cors in http function 
exports.myFunc = functions.https.onRequest((req, resp) => { 
      corsHandler(req, res, async () => { 
              // your method body 
      });
});

使用 HTTPS Callable 函数让 Firebase 处理 request/response。

// function
exports.myFunc = functions.https.onCall((data, context) => {
  const from = data.sender;
  return admin.auth().getUserByEmail(from)
      .then(function(userRecord) {
       console.log("Successfully fetched user data:", userRecord.toJSON());
       return { user: userRecord.toJSON() }
      })
      .catch(function(error) {
        console.log("Error fetching user data:", error);
      });
});
// web
 import { initializeApp } from 'firebase/app';
 import { getFunctions } from 'firebase/functions';

const app = initializeApp({
     // ...
   });
const functions = getFunctions(app);
const myFunc = httpsCallable(functions, 'myFunc');
myFunc({ sender: 'example@example.com' })
  .then((result) => {
    const data = result.data;
    console.log(data.user);
  });

花了很多时间后我发现如果我这样写我的云函数,它是有效的:

exports.myFunc = functions.https.onRequest(function(req, resp) {
  corsHandler(req, resp, async () => {
    const from = String(req.query.from); // Through the URL.
    admin.auth().getUserByEmail(from)
        .then(function(userRecord) {
          console.log("Successfully fetched user data:", 
                      userRecord.toJSON());
        })
        .catch(function(error) {
          console.log("Error fetching user data:", error);
        });
  });
});