本地无法运行Supabase Edge Functions:端口占用问题求助
端口占用导致Supabase Edge Functions启动失败的解决方法
问题详情
我编写了一个Edge Functions脚本,用于调用Gemini模型执行提示词并返回结果,但启动时因端口占用失败。
本地执行cURL请求时终端报错:
{"code":"BOOT_ERROR","message":"Worker failed to boot (please check logs)"}%
调试器报错信息:
error: Uncaught (in promise) AddrInUse: Address already in use (os error 48) const listener = Deno.listen({ ^ at Object.listen (ext:deno_net/01_net.js:534:35) at Server.listenAndServe (https://deno.land/std@0.180.0/http/server.ts:182:27) at serve (https://deno.land/std@0.180.0/http/server.ts:604:20) at startServer (file:///Users/shlokjain/Documents/dev/beacon/supabase/functions/essay-prompt/index.ts:9:19) /* point to serve function call */ at file:///Users/shlokjain/Documents/dev/beacon/supabase/functions/essay-prompt/index.ts:66:1
脚本代码:
import { serve } from "https://deno.land/std@0.180.0/http/server.ts"; const portsToTry = [54321, 8080, 8081]; async function startServer() { for (const port of portsToTry) { try { await serve(async (req) => { // 业务逻辑代码 return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json'} }) }, { port }) console.log(`Server listening on port ${port}`); break; } catch (err) { if (err instanceof Deno.errors.AddrInUse) { console.error(`Port ${port} is already in use`); continue; } else { throw err; } } } } startServer(); console.log("Hello from Functions!");
请求用的cURL命令:
curl -i --location --request POST 'http://127.0.0.1:54321/functions/v1/essay-prompt' \ --header 'Authorization: Bearer API_KEY' \ --header 'Content-Type: application/json' \ --data '{"essayPrompt":"Functions"}'
解决方法
1. 释放占用端口的进程
先找出占用目标端口的进程,以macOS/Linux为例:
lsof -i :54321
找到进程PID后,强制杀死进程:
kill -9 <PID>
Windows系统用以下命令:
netstat -ano | findstr :54321 taskkill /F /PID <PID>
2. 修复脚本的端口重试逻辑
当前脚本的serve函数是阻塞式的,一旦调用成功会一直监听,后续的console.log和循环重试逻辑根本不会执行。修改后的脚本先验证端口可用性,再启动服务:
import { serve } from "https://deno.land/std@0.180.0/http/server.ts"; const portsToTry = [54321, 8080, 8081]; async function startServer() { for (const port of portsToTry) { try { // 先创建监听,确认端口可用 const listener = Deno.listen({ port }); console.log(`Server listening on port ${port}`); // 启动服务 await serve(async (req) => { // 补充你的业务逻辑代码 const data = { /* 你的返回数据结构 */ }; return new Response(JSON.stringify(data), { headers: { 'Content-Type': 'application/json'} }) }, { listener }); break; } catch (err) { if (err instanceof Deno.errors.AddrInUse) { console.error(`Port ${port} is already in use`); continue; } else { throw err; } } } } startServer(); console.log("Hello from Functions!");
3. 使用Supabase官方本地启动命令
Supabase Edge Functions本地运行无需手动指定端口,直接用官方命令启动即可避免冲突:
supabase functions serve essay-prompt
启动后默认会在http://127.0.0.1:54321/functions/v1/essay-prompt提供服务,和你之前的cURL请求地址一致。
内容的提问来源于stack exchange,提问作者Shlok Jain
相关产品推荐
相关产品推荐

