Firebase可调用函数无效

时间:2018-05-15 22:00:38

标签: javascript node.js firebase google-cloud-functions

这是我index.js文件的一部分:

const firebase = require("firebase");
const functions = require('firebase-functions');
// Firebase Setup
const admin = require('firebase-admin');
const serviceAccount = require('./service-account.json');
const cors = require('cors')({ origin: true });
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount)
});

exports.addMessage = functions.https.onCall((data, context) => {
    const sanitizedMessage = sanitizer.sanitizeText("test");
    return admin.database().ref('/messages').push({
        text: sanitizedMessage
    }).then(() => {
        console.log('New Message written');
        return { text: sanitizedMessage };
    })
});

此功能已成功上传到Firebase。我试图使用此代码从我的Web客户端调用它:

var addMessage = firebase.functions().httpsCallable('addMessage');
addMessage({text: "test"}).then(function(result) {
    var sanitizedMessage = result.data.text;
    console.log(sanitizedMessage);
});

结果出现以下描述错误:

enter image description here

此外,Firebase控制台中没有日志。如果我直接访问该链接,我会收到一条日志消息。这意味着两件事:

  1. 我的网络客户端正确构建了我的函数的URL。
  2. 鉴于访问它会直接在Firebase控制台中生成一个日志,这意味着我的网络客户端甚至不会进行此调用。
  3. 我完全陷入困境,因为我跟随official guide

    非常感谢任何有关调试的帮助。

2 个答案:

答案 0 :(得分:0)

const functions = require('firebase-functions');
const admin = require('firebase-admin');
const cors = require('cors')({ origin: true });
admin.initializeApp();

exports.addMessage = functions.https.onCall((data, context) => {
    const sanitizedMessage = sanitizer.sanitizeText("test");
    return admin.database().ref('/messages').push({
        text: sanitizedMessage
    }).then(() => {
        console.log('New Message written');
        return { text: sanitizedMessage };
    })
});

答案 1 :(得分:0)

我已经彻底地尝试并测试了您的代码,可能存在两个问题。

我假设您打算使用此npm清理程序包:https://www.npmjs.com/package/sanitizer,因此这些问题可能是:

  1. 您不需要清洁剂包。 (你装了吗,顺便说一句?)
  2. sanitizeText不是sanitazer模块的方法,而sanitize
  3. 以下代码效果很好:

    const functions = require('firebase-functions');
    const sanitizer = require('sanitizer');
    const admin = require('firebase-admin');
    const cors = require('cors')({ origin: true });
    admin.initializeApp();
    
    exports.addMessage = functions.https.onCall((data, context) => {
        const sanitizedMessage = sanitizer.sanitize("test");
        console.log(sanitizedMessage);
    
        return admin.database().ref('/messages').push({
            text: sanitizedMessage
        }).then(() => {
            console.log('New Message written');
            return { text: sanitizedMessage };
        })
    });