首页 > 解决方案 > 将表单数据发送到 firebase 函数

问题描述

我想将数据从我的 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;
  });
...

提前致谢。

标签: javascriptfirebasegoogle-cloud-functions

解决方案


如果您使用“标准” HTTPS 云函数,则需要使用 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请求发送表单数据


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

使用这种类型,您可以使用 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 以及如何调用它)。


推荐阅读