通过HTTP触发的Firebase Cloud Function执行两次 [英] Firebase Cloud Function executing twice when triggered over HTTP

查看:44
本文介绍了通过HTTP触发的Firebase Cloud Function执行两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Firebase Cloud Functions集成到我的Ionic 3 App中.目标是创建一个云功能,该功能将使用admin SDK创建用户.

I'm trying to integrate Firebase Cloud Functions into my Ionic 3 App. The goal is to create a cloud function that will create a user using the admin SDK.

但是,如果通过HTTP触发此函数,则仅在将数据传递给它时才会执行两次,如果我只是调用没有数据的函数,则该函数将按预期执行一次.

However, when triggering this function over HTTP it will execute twice only when passing data to it, if I just call the function with no data it executes once as intended.

云功能代码:

const functions = require('firebase-functions');

exports.createUser = functions.https.onRequest((request, response) => {
  response.set('Access-Control-Allow-Origin', '*');
  response.set('Access-Control-Allow-Headers', 'Content-Type');
  console.log(request.body);
  response.status(200).send('Hello from Firebase!');
});

HTTP请求:

axios.post(functionURL, {
  data: 'some data'
})
.then(res => {
  console.log(res.data);
})
.catch(err => console.log(err));

上面的HTTP请求按预期工作,我看到来自Firebase的问候!"在控制台中只有一次,但是当我查看函数日志时,它表明它正在执行两次.

The HTTP request above works as intended and I see "Hello from Firebase! " only once in the console, however when I look at the functions logs it's showing it's being executed twice.

我是Firebase Cloud Functions的新手,因此非常感谢任何输入或建议!

I'm very new to Firebase Cloud Functions so any input or suggestions would be greatly appreciated!

推荐答案

已解决

此处找到解决方案:用于Firebase触发的云函数CORS飞行前请求功能

当我以 application/json 的形式发送数据时,它触发了CORS预检请求,这正是导致函数在传递数据时执行两次的原因.

As I was sending the data as application/json it was triggering a CORS preflight request, which is exactly what was causing the function to execute twice when passing data.

要绕过此操作,我只是将数据作为 application/x-www-form-urlencoded 字符串发送,如下所示:

To bypass this, I simply sent the data as a application/x-www-form-urlencoded string like this:

const dataStr = JSON.stringify(objectToPass);

axios({
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: `data=${dataStr}`
})

然后将主体解析回该函数中的对象,如下所示:

And then parse the body back into an object in the function like this:

const data = JSON.parse(request.body.data);

这篇关于通过HTTP触发的Firebase Cloud Function执行两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆