【问题标题】:Cloud Functions for Firebase: how to issue a request to my Cloud EndpointCloud Functions for Firebase:如何向我的 Cloud Endpoint 发出请求
【发布时间】:2017-08-09 19:27:14
【问题描述】:

当某个值写入 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。

首先,该请求使用的正确包是什么?谷歌API?请求-承诺?

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

【问题讨论】:

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


    【解决方案1】:

    更新

    Cloud Functions for Firebase 似乎阻止了对其 App Engine 服务的请求 - 至少在 Spark 计划中(即使它们都归 Google 所有 - 所以你会假设“on the same network”)。下面的请求在运行 Node.js 的本地机器上工作,但在 Functions 服务器上失败,出现 getaddrinfo EAI_AGAIN 错误,如 here 所述。显然,当您向运行在 Google 的 App Engine 上的服务器执行请求时,访问 Google API 的并不是 considered

    无法解释为什么在这里 Firebase 的拥护者会像躲避火灾一样避开这个问题。

    原答案

    想通了 - 切换到“request-promise”库:

    "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);
        });
    });
    

    【讨论】:

    • 谢谢,我发现这是一个非常有用的答案。我正在使用 Firebase Blaze 计划,我的请求通过了,使用您建议的代码。
    猜你喜欢
    • 2017-09-15
    • 2018-03-04
    • 2019-06-09
    • 2017-09-07
    • 2018-01-03
    • 2022-12-01
    • 2018-08-13
    • 2018-05-02
    • 2018-02-22
    相关资源
    最近更新 更多