我使用一个云函数在自由火花层上调用另一个云函数。
有什么特别的方法来调用另一个云函数吗?还是您只是使用标准的http请求?
我尝试直接调用另一个函数,如下所示:
exports.purchaseTicket = functions.https.onRequest((req, res) => {
fetch('https://us-central1-functions-****.cloudfunctions.net/validate')
.then(response => response.json())
.then(json => res.status(201).json(json))
})但我明白错误
https://us-central1-functions-****.cloudfunctions.net/validate请求失败,原因: getaddrinfo ENOTFOUND us-central1-functions-*****.cloudfunctions.net us-central1-functions-*****.cloudfunctions.net:443
这听起来像是防火墙阻塞了连接,尽管它是谷歌拥有的,因此它不应该被锁定。
星火计划只允许向谷歌拥有的服务发出出站网络请求。
如何使用云函数调用另一个云函数?
发布于 2017-03-14 13:20:09
您不需要通过一个全新的HTTPS调用来调用某些共享功能。您可以简单地将公共代码部分抽象成一个常规的javascript函数,其中任何一个都会调用该函数。例如,您可以像这样修改模板helloWorld函数:
var functions = require('firebase-functions');
exports.helloWorld = functions.https.onRequest((request, response) => {
common(response)
})
exports.helloWorld2 = functions.https.onRequest((request, response) => {
common(response)
})
function common(response) {
response.send("Hello from a regular old function!");
}这两个函数将做完全相同的事情,但有不同的端点。
发布于 2020-02-29 23:51:53
要回答这个问题,您可以执行https请求来调用另一个云函数:
export const callCloudFunction = async (functionName: string, data: {} = {}) => {
let url = `https://us-central1-${config.firebase.projectId}.cloudfunctions.net/${functionName}`
await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ data }),
})
}(注意,我们使用npm包‘节点-提取’作为我们的获取实现。)
然后简单地称之为:
callCloudFunction('search', { query: 'yo' })这样做是有正当理由的。我们每分钟都使用它来平平我们的搜索云功能,并让它继续运行。这大大降低了一年几美元的响应延迟。
发布于 2020-08-14 23:28:01
通过包含授权令牌,可以通过HTTP调用另一个Google函数。它需要一个主HTTP请求来计算令牌,然后在调用要运行的实际Google函数时使用该令牌。
https://cloud.google.com/functions/docs/securing/authenticating#function-to-function
const {get} = require('axios');
// TODO(developer): set these values
const REGION = 'us-central1';
const PROJECT_ID = 'my-project-id';
const RECEIVING_FUNCTION = 'myFunction';
// Constants for setting up metadata server request
// See https://cloud.google.com/compute/docs/instances/verifying-instance-identity#request_signature
const functionURL = `https://${REGION}-${PROJECT_ID}.cloudfunctions.net/${RECEIVING_FUNCTION}`;
const metadataServerURL =
'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/identity?audience=';
const tokenUrl = metadataServerURL + functionURL;
exports.callingFunction = async (req, res) => {
// Fetch the token
const tokenResponse = await get(tokenUrl, {
headers: {
'Metadata-Flavor': 'Google',
},
});
const token = tokenResponse.data;
// Provide the token in the request to the receiving function
try {
const functionResponse = await get(functionURL, {
headers: {Authorization: `bearer ${token}`},
});
res.status(200).send(functionResponse.data);
} catch (err) {
console.error(err);
res.status(500).send('An error occurred! See logs for more details.');
}
};2021年10月更新:您不需要在本地开发环境中这样做,谢谢Aman澄清了这一点
https://stackoverflow.com/questions/42784000
复制相似问题