【问题标题】:Calling a cloud function from a firebase web app从 Firebase Web 应用程序调用云函数
【发布时间】:2022-01-31 10:35:23
【问题描述】:

我正在尝试在 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).

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

【问题讨论】:

    标签: node.js firebase google-cloud-functions firebase-hosting


    【解决方案1】:

    你需要安装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 
          });
    });
    

    【讨论】:

    【解决方案2】:

    使用 HTTPS Callable 函数让 Firebase 处理请求/响应。

    // 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);
      });
    
    

    【讨论】:

      【解决方案3】:

      花了很多时间后,我发现如果我这样写我的云函数,它可以工作:

      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);
              });
        });
      });
      

      【讨论】:

        猜你喜欢
        • 2021-04-08
        • 1970-01-01
        • 2019-01-18
        • 1970-01-01
        • 1970-01-01
        • 2021-09-13
        • 2017-08-09
        • 1970-01-01
        • 2020-05-17
        相关资源
        最近更新 更多