gpt4 book ai didi

javascript - 将表单数据发送到 firebase 函数

转载 作者:行者123 更新时间:2023-12-01 01:08:59 25 4
gpt4 key购买 nike

我想将数据从我的 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 Cloud Function ,您需要使用 JavaScript 从您的网页发出 HTTP 请求。一种方法是使用 axios图书馆。

这很简单:

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

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

并且,在 JavaScript 代码中,您可以通过其 URL 调用云函数。下面是一个 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);
});

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

<小时/>

如果您想在云功能中使用“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;
// ...
});

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

关于javascript - 将表单数据发送到 firebase 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55336364/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com