使用Google Cloud Functions创建Webhook时遇“服务不可用”问题求助
问题现象
部署Cloud Functions后,使用Cloud Shell测试接口返回Service Unavailable,测试命令:
curl -m 70 -X POST https://us-central1-webhookattentive.cloudfunctions.net/function-2 \ -H "Authorization: bearer $(gcloud auth print-identity-token)" \ -H "Content-Type: application/json" \ -d '{}'
查看函数日志,发现端口占用错误:
Error: listen EADDRINUSE: address already in use :::8080 at Server.setupListenHandle [as _listen2] (node:net:1740:16) at listenInCluster (node:net:1788:12) at Server.listen (node:net:1876:7) at main (/layers/google.nodejs.functions-framework/functions-framework/node_modules/@google-cloud/functions-framework/build/src/main.js:45:14)
问题原因
代码中手动调用了app.listen(8080)启动Express服务器,但Cloud Functions的运行环境会通过Functions Framework自动监听端口(默认8080),手动启动服务器会和Framework的监听进程端口冲突,导致地址被占用。
修复步骤
删除代码中手动启动服务器的部分,移除以下代码段:
// Start the server app.listen(8080, () => { console.log('Server running on port 8080'); });
Cloud Functions会自动加载你导出的Express app实例,无需手动启动服务器。
修复后的完整代码
const express = require('express'); const { Storage } = require('@google-cloud/storage'); const app = express(); app.use(express.json()); // Create a new instance of the Storage client const storage = new Storage(); // Define your Google Cloud Storage bucket name const bucketName = 'attentivesignup'; app.post('/webhook', async (req, res) => { const webhookPayload = req.body; // Write the webhook payload to a file in Google Cloud Storage const filename = `webhook-${Date.now()}.json`; const file = storage.bucket(bucketName).file(filename); await file.save(JSON.stringify(webhookPayload), { contentType: 'application/json', gzip: true, }); console.log(`Webhook payload saved to: gs://${bucketName}/${filename}`); // Send a response back to Attentive res.status(200).send('Webhook received successfully'); }); exports.webhook = app;
验证方法
- 重新部署Cloud Functions
- 再次使用之前的curl命令测试接口,此时应返回
Webhook received successfully - 查看GCS存储桶,确认webhook payload已被保存为JSON文件
内容的提问来源于stack exchange,提问作者npatrick
相关产品推荐
相关产品推荐

