【问题标题】:send form data to firebase functions将表单数据发送到 firebase 函数
【发布时间】:2019-03-25 11:03:54
【问题描述】:

我想将数据从我的 javascript 网页发送到 firebase 云函数(HTTP 请求)。

我看过一些关于使用 Busboy 的教程,但那是在云功能方面。我想知道的是如何将它从客户端网页发送到函数。

如 Google Cloud Functions Documentation 中所述,我在 Firebase 函数中使用了以下代码。

...
busboy.on('field', (fieldname, val) => {
    // TODO(developer): Process submitted field values here
    console.log(`Processed field ${fieldname}: ${val}.`);
    fields[fieldname] = val;
  });
...

提前致谢。

【问题讨论】:

    标签: javascript firebase google-cloud-functions


    【解决方案1】:

    如果您使用“标准”HTTPS Cloud Function,您需要使用 JavaScript 从您的网页发出 HTTP 请求。一种方法是使用 axios 库。

    很简单:

    您在 html 页面的头部声明该库

    <head>
      ...
      <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
      ...
    </head>
    

    并且,在您的 JavaScript 代码中,您通过其 URL 调用 Cloud Function。这是一个带有 POST 请求的示例:

    axios.post('https://us-central1-<project-id>.cloudfunctions.net/<your-cloud-cunction-name>', {
        firstName: 'Fred',
        lastName: 'Flintstone'
      })
      .then(function (response) {
        console.log(response);
        //Do whatever you wantwith the response object, returned by the HTTPS Cloud Function
      })
      .catch(function (error) {
        console.log(error);
      });
    

    在 Cloud Function 中,您可以使用 req.body.firstNamereq.body.lastName 来获取在 POST 请求正文中传递的值。如果您不需要通过请求的正文传递值,则可以使用 GET 方法(并且可能通过查询字符串传递一些值)。


    如果您想在 Cloud Function 中使用“busboy”库来解析 'multipart/form-data' 上传请求(如您在问题中引用的示例所示),以下 Stack Overflow 答案解释了如何执行此操作使用 axios:

    axios post request to send form data


    请注意,Firebase 提供了另一种类型的 HTTP 云函数:HTTPS Callable Functions

    使用此类型,您可以使用 Firebase 提供的专用 Cloud Functions 客户端库从 Web 前端调用它。该文档显示了以下示例:

    var addMessage = firebase.functions().httpsCallable('addMessage');
    addMessage({text: messageText}).then(function(result) {
      // Read result of the Cloud Function.
      var sanitizedMessage = result.data.text;
      // ...
    });
    

    查看文档,其中详细解释了所有步骤(如何编写 Cloud Function 以及如何调用它)。

    【讨论】:

    • 不使用axios之类的外部库有没有其他方法?
    • 是的,您可以在 Ajax 中进行 HTTP 调用或使用 jQuery 方法(请参阅此文档 medium.freecodecamp.org/…),但我建议使用 Axios,它对用户非常友好,并且还返回了 Promise(即符合 Firebase Web/JavaScript SDK 处理异步任务的方式)
    • @BasilVictor 查看我关于如何发送 'multipart/form-data' 上传请求的更新
    • 我已经实现了axios,但似乎有错误。从源“localhost”访问“us-central1-test-ec013.cloudfunctions.net/addData”处的 XMLHttpRequest 已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头。你能告诉我一个快速的解决方法吗?
    【解决方案2】:

    我知道,axios 不是像 formData(图片和其他)这样的对象的最佳解决方案,如果您使用 fetch 可能会更好?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-12
      • 1970-01-01
      • 2019-10-19
      • 1970-01-01
      • 2014-01-20
      • 2017-08-07
      相关资源
      最近更新 更多