Vite+React项目Netlify Functions运行异常求助
解决Netlify Functions替代Express代理时的连接拒绝问题
问题场景
将用于隐藏API密钥的Node/Express代理服务器迁移到Netlify Functions时出现异常:
- 本地通过
npm run dev启动Vite,同时单独运行node server/server.js,前端请求/api/hello正常响应 - 使用
netlify dev运行时,前端请求触发Vite代理错误,提示连接被拒绝(ECONNREFUSED)
相关配置与代码
vite.config.js 代理配置
server: { // port: 3000, proxy: { "/api": { target: "http://localhost:5022", changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ""), secure: false, }, }, },
netlify.toml 配置
[build] command = "npm run build" publish = "dist" functions = "functions" [[redirects]] from = "/*" to = "/index.html" status = 200 [[redirects]] from = "/api/*" to = "/.netlify/functions/:splat" status = 200
netlify/functions/api.mjs 原代码
import { config } from "dotenv"; import express from "express"; config(); const api = express(); api.use(express.json()); ... api.get("/hello", (req, res) => res.send("Hello from api.mjs!")); app.listen(process.env.PORT || 5022, () => { console.log(`Server listening on port ${process.env.PORT || 5022}`); });
src/component/Sample.jsx 请求代码
useEffect(() => { const callHello = async () => { try { const response = await axios.get('/api/hello'); console.log("Response:", response.data); } catch (error) { console.error("Error:", error); } }; callHello(); },[])
错误提示
8:57:13 AM [vite] http proxy error: /hello AggregateError [ECONNREFUSED]: at internalConnectMultiple (node:net:1128:18) at afterConnectMultiple (node:net:1693:7)
错误原因
- Netlify Functions代码写法错误:使用了Express的
app.listen启动服务器,但Netlify Functions不需要手动监听端口,需导出符合要求的处理函数 - Vite代理与Netlify环境冲突:
netlify dev运行时,原本地Express服务器未启动,但Vite代理仍指向localhost:5022,导致连接失败 - 重定向规则不精确:
netlify.toml中重定向未指定具体的Function文件名,可能导致请求无法正确路由
修复步骤
1. 修正Netlify Functions代码
安装serverless-http工具,将Express应用转换为Netlify Functions兼容格式:
npm install serverless-http
修改netlify/functions/api.mjs:
import { config } from "dotenv"; import express from "express"; import serverless from "serverless-http"; config(); const api = express(); api.use(express.json()); // 保留原有路由逻辑 api.get("/hello", (req, res) => res.send("Hello from api.mjs!")); // 导出serverless处理函数,替代listen export const handler = serverless(api);
2. 调整Vite代理的环境适配
在vite.config.js中根据环境变量判断是否启用本地代理,netlify dev环境下关闭代理,让请求走Netlify重定向:
import { defineConfig } from 'vite'; export default defineConfig({ server: { proxy: process.env.NETLIFY_DEV ? {} // Netlify开发环境下禁用Vite代理 : { "/api": { target: "http://localhost:5022", changeOrigin: true, rewrite: (path) => path.replace(/^\/api/, ""), secure: false, }, }, }, });
3. 完善Netlify重定向规则
修改netlify.toml中的API重定向规则,指定具体的Function文件名:
[build] command = "npm run build" publish = "dist" functions = "functions" [[redirects]] from = "/*" to = "/index.html" status = 200 [[redirects]] from = "/api/*" to = "/.netlify/functions/api/:splat" # 明确指向api.mjs这个Function status = 200
4. 调整开发启动流程
- 本地传统开发:运行
npm run dev+node server/server.js - Netlify本地开发:直接运行
netlify dev,无需启动原Express服务器,Netlify会自动加载Functions
验证
启动netlify dev后,前端请求/api/hello应正常返回"Hello from api.mjs!",无连接拒绝错误。
内容的提问来源于stack exchange,提问作者sandraqu
相关产品推荐
相关产品推荐

