【问题标题】:Firebase functions query parameters are nullFirebase 函数查询参数为空
【发布时间】:2021-12-07 01:00:19
【问题描述】:

我在将查询参数传递给我的 firebase(谷歌云)函数时遇到困难,它们一直是空的,但函数正常完成。任何人都可以找出问题所在吗?

云功能码

exports.message = functions.https.onRequest((request, response) => {
   functions.logger.log("log query");
   functions.logger.log(request.query);
  response.json({result: `done`});
});

本地应用代码:

export const sendPushNotification = async (options) => {
  try {
    const db = firebase.firestore();
    const fbFunctions = firebase.functions();

    const message = fbFunctions.httpsCallable("message");
   message({text:"asdfasdf"})
  
  } catch (error) {
    console.log({ error });
    switch (error.code) {
      default:
        return {
          error: "Error.",
        };
    }
  }
};

【问题讨论】:

标签: react-native google-cloud-functions


【解决方案1】:

无法使用 Firebase Functions SDK 调用 onRequest 类型的函数。 Firebase SDK 实现了您使用 onCall 声明的 callable function 的客户端。您在这里使用 onRequest,这意味着您正在编写一个标准的 HTTP 类型函数。对于此类函数,您应该使用标准 HTTP 客户端(而不是 Firebase SDK)。如果您确实想使用 Firebase SDK 来调用您的函数,则必须改为编写一个可调用函数。请注意,可调用函数have their own spec,您将无法轻松调用它们,例如来自邮递员。

使用functions.https.onCall 创建一个HTTPS 可调用函数。这个方法有两个参数:数据和可选的上下文: 这是应该为您工作的代码:

exports.addMessage = functions.https.onCall((data, context) => {
const text = data.text;
if (!(typeof text === 'string') || text.length === 0) {
throw new functions.https.HttpsError('invalid-argument', 'The function must be called with ' +
        'one arguments "text" containing the message text to add.');
}

if (!context.auth) {
throw new functions.https.HttpsError('failed-precondition', 'The function must be called ' +
        'while authenticated.');
const uid = context.auth.uid;
const name = context.auth.token.name || null;
const picture = context.auth.token.picture || null;
const email = context.auth.token.email || null;

const sanitizedMessage = sanitizer.sanitizeText(text); // Sanitize the message.
return admin.database().ref('/messages').push({
    text: sanitizedMessage,
    author: { uid, name, picture, email },
}).then(() => {
  console.log('New Message written');

return { text: sanitizedMessage };
})

.catch((error) => {
throw new functions.https.HttpsError('unknown', error.message, error);
});

});

通过以下步骤设置客户端开发环境:

  1. Add Firebase to your Web App
  2. 将 Firebase 核心和 Cloud Functions 客户端库添加到您的应用中:

3. 运行 npm install firebase@8.10.0 --save
4. 手动要求 Firebase 核心和 Cloud Functions:

const firebase = require("firebase");
// Required for side-effects
require("firebase/functions");
  1. 使用以下方法初始化客户端 SDK:

  1. 使用以下方法调用函数:

【讨论】:

    猜你喜欢
    • 2016-04-07
    • 2018-05-08
    • 1970-01-01
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-06-09
    • 2016-03-07
    • 1970-01-01
    相关资源
    最近更新 更多