Firebase的云端功能:如何向我的Cloud端点发出请求
问题描述:
我想在向Firebase数据库写入特定值时向我的云端点项目发出请求。我找不到如何在Node.js中执行对端点的请求的任何示例。这是我想出迄今:Firebase的云端功能:如何向我的Cloud端点发出请求
"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)
。
答
更新
看来,云计算功能的火力地堡块请求他们的App Engine服务 - 至少在星火计划(即使它们都是由谷歌拥有的 - 所以你认为“on the same network “)。下面的请求在运行Node.js的本地机器上运行,但在函数服务器上运行失败,出现getaddrinfo EAI_AGAIN
错误,如here所述。显然,当您向在Google App Engine上运行的服务器执行请求时,它不是considered访问Google API。
无法解释为什么Firebase在这里主张避免像火灾这样的问题。
原来的答案
想通了 - 切换到 '请求承诺' 库:
"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计划,并使用您建议的代码通过了我的请求。 – CKP78