【发布时间】:2020-09-13 03:07:39
【问题描述】:
问题总结:我想从我的 Firebase Cloud Function 触发一个 POST 请求到我当前在本地计算机上运行的 node.js 后端。函数开始执行,但 POST 调用从未到达后端。
开发环境:
- Firebase 实时数据库:Blaze 计划。 DB 中的新条目会触发 Cloud Function。
- Firebase 云功能:axios 0.19.2、firebase-admin 8.10.0、firebase-functions 3.6.1。
- 后端:节点 v12.14.1,http://XXX.XXX.X.XX:3000
预期结果:来自 Firebase Cloud Function 的 POST 调用触发 node.js 后端中的路由以处理在 POST 调用中接收到的数据。
实际结果:POST 调用永远不会到达当前在本地计算机上运行的 node.js 后端。登录 Firebase Cloud Functions 控制台:
函数执行耗时 60012 毫秒,完成状态为:'timeout'
到目前为止我尝试了什么?
- 来自 POSTMAN 的 POST 调用顺利到达我的后端。
- 将 axios 替换为 request-promise-native 以进行 POST 调用。
- 将http://XXX.XXX.X.XX:3000 替换为http://localhost:3000。
- 使用 axios 的 .then().catch() 语法。
- 将 axios 的 async await 语法与 try & catch 结构结合使用。
Firebase 云函数代码:
const functions = require('firebase-functions');
const axios = require('axios');
const admin = require('firebase-admin');
admin.initializeApp();
const BACKEND_URL = 'http://XXX.XXX.X.XX:3000';
exports.triggerNotification = functions.database.ref('/sessions/{sessionID}/{message}')
.onCreate(function(snapshot, context) {
const createdContent = snapshot.val();
const config = { headers: { 'Content-Type': 'application/json' } };
if (!createdContent) {
return;
}
return axios.post(`${BACKEND_URL}/notification/trigger`, { createdContent } ,config);
});
Node.js 后端代码:
router.post('/trigger', function (req, res) {
console.log('req.body', req.body);
res.status(200).send('Post request received');
});
【问题讨论】:
-
看起来您正在使用 IP 地址,并且后端正在本地计算机上运行,因为您尝试了 localhost 并且它的格式与您的代码中的格式类似。您说邮递员有效,但您是从网络外部尝试吗?我的猜测是连接被阻塞了。您可以尝试像ngrok 这样公开本地服务器的服务吗?还要确保使用 https 进行尝试。
-
@JasonGoemaat:我感激不尽。如果你愿意,你可以写下答案,我会赞成并删除我的。请告诉我。我不想把你的回答归功于自己。
标签: node.js firebase-realtime-database axios google-cloud-functions