javascript - 将表单数据发送到 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;
});
...
提前致谢。
解决方案
如果您使用“标准” 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.firstName
并req.body.lastName
获取在 POST 请求正文中传递的值。如果您不需要通过请求的正文传递值,则可以使用 GET 方法(并且可能通过查询字符串传递一些值)。
如果您想在 Cloud Function 中使用“busboy”库来解析'multipart/form-data'
上传请求(如您在问题中引用的示例所示),以下 Stack Overflow 答案解释了如何使用 axios 进行此操作:
请注意,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 以及如何调用它)。
推荐阅读
- ruby-on-rails - 如何使用 rspec 测试 ActionCable 和 Devise?
- java - 搜索数组的问题
- composer-php - 我应该把 composer.json 文件放在哪里?
- javascript - 解析 afterFind,添加到响应的对象是客户端中的指针
- python - 如何在 pqytgraph 的 2 个图中同步 x 轴
- android - KeyPermanentlyInvalidatedException 不起作用
- django - Django - 需要可选的表单字段
- java - 如何播放 mp4(实际上是 GIF 转换为 mp4)?
- android - MIFARE 卡在 Android 设备上复制
- javascript - 订阅 paramMap 会破坏路由示例?