如果您使用“标准”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.firstName 和 req.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 以及如何调用它)。