适用于Firebase的云功能:如何向我的Cloud Endpoint发出请求

时间:2017-03-26 16:53:53

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

当我在firebase数据库中写入某个值时,我试图向我的云端点项目发出请求。我无法找到如何在Node.js中对端点执行请求的任何示例。这是我到目前为止所提出的:

"use strict";
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const gapi = require('googleapis');

admin.initializeApp(functions.config().firebase);

exports.doCalc = functions.database.ref('/users/{uid}/calc').onWrite(event => {
    return gapi.client.init({
            'apiKey': 'AIzxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
            'clientId': '1234567890-xxx.apps.googleusercontent.com',
            'scope': 'donno what to put here'
       }).then(function() {
           return gapi.client.request({
               'path': 'https://myproj.appspot.com/_ah/api/myApi/v1',
               'params': {'query': 'startCalc', uid: event.params.uid }
           })
       }).then(function(response) {
           console.log(response.result);
       }, function(reason) {
           console.log('Error: ' + reason.result.error.message);
       });
});

触发后,功能'日志鲸鱼喷水:TypeError: Cannot read property 'init' of undefined。即没有认识到gapi.client。

首先,该请求使用的正确包是什么? googleapis?请求承诺?

其次,我是否为端点调用设置了正确的路径和参数?假设端点函数为startCalc(int uid)

1 个答案:

答案 0 :(得分:7)

<强>更新

Firebase的Cloud Functions似乎阻止了对其App Engine服务的请求 - 至少在Spark计划中(即使它们都归谷歌所有 - 所以你要假设&#34; {{ 3}}&#34)。下面的请求适用于运行Node.js的本地计算机,但在函数服务器上失败,出现getaddrinfo EAI_AGAIN错误,如on the same network所述。显然,当您向在Google的App Engine上运行的服务器发出请求时,here无法访问Google API。

无法解释为什么Firebase的倡导者会像火一样避开这个问题。

原始答案

想出来 - 切换到&#39;请求承诺&#39;图书馆:

"use strict";
const functions = require('firebase-functions');
const request = require('request-promise');
const admin = require('firebase-admin');

admin.initializeApp(functions.config().firebase);

exports.doCalc = functions.database.ref('/users/{uid}/calc').onWrite(event => {
    return request({
        url: `https://myproj.appspot.com/_ah/api/myApi/v1/startCalc/${event.params.uid}`,
        method: 'POST'
    }).then(function(resp) {
        console.log(resp);
    }).catch(function(error) {
        console.log(error.message);
    });
});